我在一个网页上有2个框架,左边的框架填充了来自javascript对象的国家名称列表。每个国家也是主对象中的一个对象,并有4个名称/值属性。我正在使用附加到主体onload的以下函数:
function populateList() {
var list = top.frames[0].document;
list.open()
list.write("<h2>Countries</h2><ul>");
for ( name in euMem ){
if( typeof name !== 'object' ){
list.write( '<li><a href="" onclick="updateFrame('' + name + '');">' + name + '</a></li>' );
}
}
list.write("</ul>");
list.close();
}
当用户单击左边的一个国家名称时,它打算运行这个函数:
function updateFrame( country ) {
var infoFrame = top.frames[1].document;
infoFrame.open();
var size = Object.size(euMem[country]);
infoFrame.writeln("<h1>Information for " + country + "</h1>");
for( prop in euMem[country] ){
infoFrame.writeln(prop + " : " + euMem[country][prop] + "<br>" );
}
infoFrame.close();
}
这似乎在Chrome上工作得很好,但在Firefox上,我得到参考错误,说明updateFrame未定义。当我硬编码updateFrame直接到HTML中,它在firefox上没有任何问题,但当它与文档一起编写时。写I get the error.
为什么这个不能在Firefox上工作?
编辑:下面是我编写的一个快速脚本,用于测试最基本的版本:
<html>
<head>
<title>InfoPane</title>
<script type="text/javascript">
function test(name){
alert(name);
}
function load(){
document.write("<button onclick='test('John Doe');'>Alert Me!</button>");
}
</script>
</head>
<body onload="load();">
</body>
</html>
以上内容不能在Firefox上运行…
我能够让这段代码作为一个基本示例工作,但无法将其扩展到我上面的代码中以使其发挥作用:
<html>
<head>
<title>InfoPane</title>
<script type="text/javascript">
function test(){
alert(this.name);
}
function load(){
var btn = document.createElement('button');
btn.name = 'John Doe';
btn.onclick = test;
btn.innerHTML = 'Alert Me!';
document.body.appendChild(btn);
}
</script>
</head>
<body onload="load();">
</body>
</html>
这是因为Firefox遵循了规范,而Chrome没有。
在最基本的版本中,页面在全局对象上定义了一个属性,其名称为"test",其值为一个函数。然后加载事件处理程序运行并调用document.write
,它执行隐式document.open
。由于此时文档不再加载,因此旧文档的内容将被清除。到目前为止,这在Firefox和Chrome中都是一样的。
它们的不同之处在于,在每个规范中,在Firefox中,不再加载的文档上的open
将为文档创建一个新的全局对象。当然,这个新的全局对象没有名为test
的属性。另一方面,Chrome保持旧的全局(和各种其他状态从旧文档,如事件处理程序,间隔计时器等)。
如果你打算用document.open
重写文档,并希望它们能够调用实用程序函数,你想把这些实用程序函数放在其他框架中,其全局你不会一直吹走。
尝试使用window.parent.updateFrame(...)