javascript - How can i bind an event to an element inside a local iframe? - Stack Overflow

Firstly both the parent page and the iframe are hosted on the same server (my localhost on WAMP) so sam

Firstly both the parent page and the iframe are hosted on the same server (my localhost on WAMP) so same origin policy should not be an issue here.

I can't get the trigger to work. My iframe has the id of iframe.

$(window).load(function(){
  //iframe ad hovers
  $('#iframe').contents().find('body div').click(function(){
    alert('do something here');
  });
}); 

what am i doing wrong?

Firstly both the parent page and the iframe are hosted on the same server (my localhost on WAMP) so same origin policy should not be an issue here.

I can't get the trigger to work. My iframe has the id of iframe.

$(window).load(function(){
  //iframe ad hovers
  $('#iframe').contents().find('body div').click(function(){
    alert('do something here');
  });
}); 

what am i doing wrong?

Share Improve this question edited Oct 14, 2010 at 15:32 Haroldo asked Oct 14, 2010 at 14:56 HaroldoHaroldo 37.4k47 gold badges131 silver badges169 bronze badges 3
  • 1 missing single quote ' and missing semicolon are typos? Beside that it looks pretty good to me. – jAndy Commented Oct 14, 2010 at 14:58
  • 1 Are you sure that the iframe content has loaded before the javascript executes? Remember that the parent page can call is_loaded before the iframe page has loaded. – Blair McMillan Commented Oct 14, 2010 at 15:00
  • any links / code for how i should call is_loaded() ? thanks – Haroldo Commented Oct 14, 2010 at 15:34
Add a ment  | 

2 Answers 2

Reset to default 7

I'm not sure the browser's going to propagate a "click" event from the window context of the <iframe> out to the containing window. Does the document loaded into the <iframe> have its own copy of jQuery? If so, you can try this:

$('#iframe').contents().$.find('body div').click(function(){
  alert('do something here);
});

That change makes the jQuery code in the <iframe> window handle the event.

Well I think that @jAndy is right and that should work as is - but you have to make sure the document in the frame is loaded. Try this:

$('#iframe').load(function() {
  $(this).contents().find('body div').click(function() { alert("hi"); });
});

Your code is not wrong; i think the only mistake you are doing is that you are asking for the iframe's content on the parent page load which means at this stage the iframe has not been loaded yet.

Try my quick example http://jsfiddle/UFM44/4/ It is same as your code but i trigger it after clicking on "now" link. if you then click on the logo you can see the alert() message.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744768014a4592580.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信