最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can jQuery bind to an iframe's onload event? - Stack Overflow

programmeradmin5浏览0评论

I know that jQuery can’t bind to a file input’s onchange event. Is it also the case that it can’t bind to an inframe’s onload event?

With this HTML,

<iframe src="" onload="alert('js alert');"></iframe>

and this javascript,

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

I get the alert js alert, not jq alert, so jQuery is not binding to the onload event.

Demo on JSFiddle.

I can’t understand why jQuery cannot bind to the onload event in time (as ThiefMaster said). Is onload so different from other events?

I know that jQuery can’t bind to a file input’s onchange event. Is it also the case that it can’t bind to an inframe’s onload event?

With this HTML,

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

and this javascript,

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

I get the alert js alert, not jq alert, so jQuery is not binding to the onload event.

Demo on JSFiddle.

I can’t understand why jQuery cannot bind to the onload event in time (as ThiefMaster said). Is onload so different from other events?

Share Improve this question edited May 23, 2017 at 12:27 CommunityBot 11 silver badge asked Oct 26, 2011 at 8:02 rhapsodynrhapsodyn 3,3625 gold badges30 silver badges36 bronze badges 1
  • @AwaisQarni. I've rewritten the question. Does it make more sense to you now? – TRiG Commented Feb 14, 2014 at 9:42
Add a ment  | 

2 Answers 2

Reset to default 3

The event has already fired at the point where you register the event handler. If you need to handle the onload event and want to avoid ugly inline event handlers, create the iframe through jQuery and attach the event handler before setting the url or attaching it to the document.

In your code, you can't catch the onload event because the event already fired and flew away at that time.

Here is a solution to catch the event:

HTML

<iframe src=""></iframe>

JS

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

When you provide the src, the load/error event fired. So, before provide src, bind events you want to handle.

You can also use this trick to <img>!

发布评论

评论列表(0)

  1. 暂无评论