javascript 如何使用 JQuery 将事件处理程序绑定到 iframe 的 onload?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11162650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:14:07  来源:igfitidea点击:

How to bind an event handler to an iframe's onload with JQuery?

javascriptjqueryiframe

提问by JeremyB

I'm having some trouble getting binding to work with JQuery.

我在绑定以使用 JQuery 时遇到了一些麻烦。

<iframe id="wufooFormz7x3k1" height="281" allowtransparency="true" frameborder="0" scrolling="no" style="width:100%;border:none" src="http://foo111.com"></iframe>

<script>
jQuery('#wufooFormz7x3k1').ready(function()
{
  jQuery('#wufooFormz7x3k1').bind('onload', alert('hi1'));
  jQuery('#wufooFormz7x3k1').bind('onload', function() { alert('hi2') });
});
</script>

The first bind generates an alert but then throws this error, and won't trigger alert for any subsequent loads of the iframe (which is what I'm trying to detect).

第一个绑定会生成一个警报,但随后会引发此错误,并且不会为 iframe 的任何后续加载触发警报(这是我试图检测的内容)。

Uncaught TypeError: Cannot read property 'handler' of undefined and won't be triggered for subsequent onloads.

The second bind doesn't trigger at all.

第二个绑定根本不会触发。

Ideally, what I want is to bind against the iframe's onload so I can generate an alert each and every time the iframe is reloaded.

理想情况下,我想要的是绑定 iframe 的 onload,这样我就可以在每次重新加载 iframe 时生成警报。

回答by Kevin B

Use the load event.

使用加载事件。

jQuery('#wufooFormz7x3k1').bind('load', function() { alert('hi2') });

The first attempt alerts because you are executing the alert and passing the return value of the alert as a function, however that return value is not a function therefore an error occurs.

第一次尝试发出警报是因为您正在执行警报并将警报的返回值作为函数传递,但是该返回值不是函数,因此会发生错误。

Also, the following isn't needed and doesn't really do what you think it does.

此外,以下内容不是必需的,也没有真正做到您认为的那样。

jQuery('#wufooFormz7x3k1').ready(function()

That ignores the '#wufooFormz7x3k1'and uses documentinstead. Since the script is located directly after the iframe tag, you can omit it because the iframe will be ready.

那会忽略'#wufooFormz7x3k1'和 使用document。由于脚本直接位于 iframe 标记之后,您可以省略它,因为 iframe 将准备就绪。