如何阻止iFrame重新加载

1 javascript iframe

我试图通过在onload事件中添加一个参数将参数传递给iFrame,如下所示:

<iframe name="myframe" src="http://test.com/hello" onload=" frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();">

</iframe>
Run Code Online (Sandbox Code Playgroud)

(getUserName是我的自定义函数)

但是iFrame一直在反复加载.如何使用javascript(而不是任何js框架)来阻止这种情况?

注意:出于某些原因,我只能编写内联JavaScript脚本.

Fel*_*ing 5

您可以设置全局标志(选择不与任何其他名称冲突的适当名称):

if (window.frames['myframe'] && !window.userSet){
    window.userSet = true;
    frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以为元素设置自定义属性:

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();
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不必再次调用事件处理程序,则可以将其删除:

if (window.frames['myframe']){
    this.onload = null;
    this.setAttribute('onload', '');
    frames['myframe'].location.href='http://test.com/hello?uname='+getUserName();
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句.你有什么if声明?true无论如何,我认为它永远都是.