2011-02-23 41 views
2

我在ID为#editor_frame的页面上有一个子iframe。 iframe内部是一个小型的jquery小部件(不是来自widget工厂的jquery ui-widget),它在用户交互后触发简单的'change'事件。绑定到子iframe中的自定义事件?

我试图绑定到从父页面事件......

$('#editor_iframe').contents().find('#uielement').bind('change', function(){....}); 

没有运气都没有。在做了一些头发拉动研究之后,我猜想iframe中的事件绑定到该窗口内的jquery命名空间中......如果这是正确的,我如何才能访问iframe窗口中的jquery命名空间?

任何接受者?

回答

5

您可以从父访问的JavaScript在孩子的iframe通过以下方式:

document.getElementById('editor_iframe').contentWindow.yourfunction() 

同样,由于jQuery是只是一个功能,您可以访问的iframe的jQuery例如像这样:

document.getElementById('editor_iframe').contentWindow.$(yourjquery)... 
+0

你能解释你如何替换绑定到该事件。 – user1736947 2014-07-15 21:35:35

+0

请解释如何实际执行绑定。 – 2015-02-15 15:23:22

0

Erik,今天我遇到了类似的问题。

我发现我的javascript函数在iframe甚至完成加载之前运行。 试试这个:

$('#editor_iframe').load(function() { 
    $(this) 
    .contents() 
    .find('#uielement') 
    .bind('change', function() { 
     // do stuff 
    }); 
}); 
+0

欣赏的答复,但我的结合已经加载函数内就像你所说的那样。 – 2011-02-23 00:27:23

0

我有同样的问题,但迄今为止所提供的解决方案并没有解决这个问题对我来说。在我看来,现有的解决方案并不直接回答这个问题。所以这是我的解决方案。

重述问题:在父页面中,我想监听子页面触发的事件。

解决方案:解决这一神秘的关键是认识到,在特定窗口中运行的jQuery实例彼此隔离。所以当你在孩子中触发一个事件时,只有孩子的jQuery实例可以监听它。解决方案是将侦听器添加到在父窗口中调用函数的子窗口。

在子页面触发事件:

$(document).trigger("myCustomEvent"); 

父页面事件处理代码:

var $iframe = $("#theIframe"); 

// Wait for the iframe to finish loading... 
$iframe.on("load", function() { 
    // Bind an event handler to the iframe's instance of jQuery, listening for the event called "myCustomEvent". 
    $iframe[0].contentWindow.$($iframe[0].contentWindow.document).on("myCustomEvent", function() { 
     // The code in that you put into this anonymous function resides in and will 
     // run in the context of the parent page. 
    }); 
}); 
相关问题