好吧,我有一个包含框架集的页面。其中一个框架包含一个 asp 页面,其中包含用 javascript 编写的脚本。 此脚本需要能够访问包含在另一个框架(框架集中)内的 asp 页面的内容。以下是框架集代码的示例:
<frameset name="foo">
<frame name="frame1" src="mydomain/path/of/the/page.asp">
<frame name="frame2" src="mydomain/path/of/the/other/page.asp">
所以基本上frame1中包含的页面内的脚本尝试访问frame2中包含的页面内的内容(更具体地说是尝试插入DOM元素)。
两个框架都位于同一域(和子域),因此跨脚本应该不是问题。我无法编辑脚本之外的代码,因此我被迫使用框架。这是我当前的代码:
//Ideally, I would like to make sure the page contained within frame2 is loaded before trying to access it's elements. I still need to figure that one out.
$(document, window.parent).ready( function () {
//Assign id "foo" to frame2 using jQuery
$('frame[name="foo"]', window.parent.document).attr("id", "foo");
var doc;
var testNode;
var frmObj = window.parent.document.getElementById('foo');
if (frmObj.contentDocument) { // DOM
doc = frmObj.contentDocument;
}
else if (frmObj.contentWindow) { // IE
doc = frmObj.contentWindow.document;
}
if (doc) {
testNode = doc.createElement('div');
testNode.Id = "testNode";
doc.getElementByTagName('body').appendChild(testNode);
}
});
包含 getElementByTagName 的行在 IE 10 中引发错误:
SCRIPT438: Object doesn't support property or method 'getElementByTagName'
文档对象似乎没有任何名为 getElementByTagName 的方法。在这种情况下,人们可能会说文档对象不存在,这是荒谬的,因为我在尝试调用它的方法之前已经测试了它的存在。知道了这一切,我们如何解决这个问题?
注释:
- 我无法使用其他浏览器测试该问题,因为所有页面所需的外部代码都使用 vbscript。
- id“foo”已成功添加到frame2。
非常感谢!
最佳答案
HTML5 不支持框架,如果您有正确的文档类型声明,您会看到一个空白页面。
无论如何,不需要使用 jQuery,这更简单:对于 frameset
窗口,您使用 top
引用always,所有框架窗口无论您想在哪里引用它们,您都可以使用 top.frame_name
(不需要 id
)来捕获它们。当您需要文档时,它就位于 window
对象下。在您的情况下: top.frame1.document
或 top.document
。
另请注意,foo
是frameset
的名称,而不是任何框架。因此 $('frame[name="foo"]', window.parent.document).attr("id", "foo");
没有按照您的预期进行。 (或者可能只是帖子中的拼写错误?)
这应该可以完成这项工作,尽管在 frame2
中的 body
存在之前,top
可能已经准备好很长一段时间。
$(document, top).ready(function () {
var testNode,
frmObj = top.frame2,
doc = frmObj.document;
if (doc) {
testNode = doc.createElement('div');
testNode.id = 'testNode';
doc.body.appendChild(testNode);
}
});
关于javascript - 如何从另一个框架访问框架的文档对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17074273/