我正在尝试通过在 onload 事件中添加参数来将参数传递给 iFrame,如下所示:
<iframe name="myframe" src="http://test.com/hello" onload=" frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();">
</iframe>
(getUserName 是我的自定义函数)
但是 iFrame 不断加载。如何仅使用 javascript(而不是任何 js 框架)来阻止它?
注意:由于某些原因,我只能编写内联 javascript 脚本。
最佳答案
您可以设置一个全局标志(选择一个不与任何其他名称冲突的适当名称):
if (window.frames['myframe'] && !window.userSet){
window.userSet = true;
frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
或者,您可以为元素设置自定义属性:
var userSet = this.getAttribute('data-userset');
if (window.frames['myframe'] && !userSet){
this.setAttribute('data-userset', 'true');
frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
或者如果您以后不必再次调用事件处理程序,则可以将其删除:
if (window.frames['myframe']){
this.onload = null;
this.setAttribute('onload', '');
frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
顺便说一句。您有什么 if
语句?我认为无论如何它总是 true
。
关于javascript - 如何阻止 iFrame 重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6676358/