【问题标题】:Can jQuery bind to an iframe's onload event?jQuery 可以绑定到 iframe 的 onload 事件吗?
【发布时间】:2011-10-26 08:02:06
【问题描述】:

我知道 jQuery 无法绑定到文件输入的 onchange 事件。是不是也不能绑定inframe的onload事件?

有了这个 HTML,

<iframe src="http://jsfiddle.net" onload="alert('js alert');"></iframe>

还有这个 javascript,

$("iframe").live("onload",function(){alert('jq alert');});

我收到警报 js alert,而不是 jq alert,所以 jQuery 没有绑定到 onload 事件。

Demo on JSFiddle.

我不明白为什么 jQuery 不能及时绑定到onload 事件(如ThiefMaster said)。 onload和其他事件有那么大的区别吗?

【问题讨论】:

  • @AwaisQarni。我已经重写了这个问题。现在对你来说更有意义了吗?

标签: javascript jquery iframe onload


【解决方案1】:

事件已在您注册事件处理程序的位置触发。如果您需要处理 onload 事件并希望避免丑陋的内联事件处理程序,请通过 jQuery 创建 iframe 并在设置 url 或将其附加到文档之前附加事件处理程序。

【讨论】:

  • 有可能,看我的回答
  • 不明白为什么jquery不能及时绑定onload事件。 Onload 与其他事件有什么不同?
  • 你能告诉我一个“通过jQuery创建iframe并在设置url或将其附加到文档之前附加事件处理程序”的例子吗??
【解决方案2】:

在您的代码中,您无法捕获 onload 事件,因为该事件当时已经触发并飞走了。

以下是捕捉事件的解决方案:

HTML

<iframe src=""></iframe>

JS

$(document).ready(function() {
  $("iframe").load(function() { alert('load complete'); });
  $("iframe").error(function() { alert('error occurs'); });
  $("iframe").attr("src", "http://google.com");
});

当您提供src 时,会触发加载/错误事件。所以,在提供src之前,绑定你要处理的事件。

你也可以用这个技巧&lt;img&gt;

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 2012-04-24
    • 2012-09-06
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    相关资源
    最近更新 更多