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

javascript - Bind to events inside dynamically created iframe - Stack Overflow

programmeradmin3浏览0评论

I need to bind to an event (say a click on an arbitrary <input>) inside an iframe that is created dynamically after the user performs a certain action. The code that appends the iframe AND the code inside the iframe is not mine and I cannot change it in any way (this is a CMS admin panel).

How can I listen to the events using jQuery 1.6 (again, this is not my choice, I'm stuck with it). I thought delegate() might be what I want:

$('body').delegate('iframe input', 'click', function(e) {
    alert('bingo?');
});

But the above does not alert when an input is clicked. The below, however, works as expected:

$('body').delegate('input', 'click', function(e) {
    alert('bingo?');
});

But this is outside the iframe.

The src of iframe points to the same domain, obviously.

Any help or just a prod in the right direction is greatly appreciated.

I need to bind to an event (say a click on an arbitrary <input>) inside an iframe that is created dynamically after the user performs a certain action. The code that appends the iframe AND the code inside the iframe is not mine and I cannot change it in any way (this is a CMS admin panel).

How can I listen to the events using jQuery 1.6 (again, this is not my choice, I'm stuck with it). I thought delegate() might be what I want:

$('body').delegate('iframe input', 'click', function(e) {
    alert('bingo?');
});

But the above does not alert when an input is clicked. The below, however, works as expected:

$('body').delegate('input', 'click', function(e) {
    alert('bingo?');
});

But this is outside the iframe.

The src of iframe points to the same domain, obviously.

Any help or just a prod in the right direction is greatly appreciated.

Share Improve this question asked Jun 18, 2012 at 17:34 bububababububaba 2,8706 gold badges26 silver badges29 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 18

This 'iframe input' does not selects input elements inside the iframe.

You can bind the event like

$('body iframe').contents().find('input').bind('click',function(e) {
    alert('bingo?');
 });

I think You can also use something like

$('body iframe').contents().find('body').delegate('input','click',function(e) {
    alert('bingo?');
 });

To detect if the iframe has been fully loaded, use the method described in this answer https://stackoverflow.com/a/5788723/344304

Add In the main/parent document:

function iframeLoaded() {
    $('body iframe').contents().find('input').bind('click',function(e) {
        alert('bingo?');
     });
}

Add In the iframe document:

window.onload = function() {
    parent.iframeLoaded();
}

Or use

$('body iframe').load(function(){
     $('body iframe').contents().find('input').bind('click',function(e) {
            alert('bingo?');
         });
});
发布评论

评论列表(0)

  1. 暂无评论