javascript JQUERY,向 iFrame 中的项目添加事件侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3273789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQUERY, Adding an Event Listener to Items in an iFrame?
提问by AnApprentice
Given an iframe with <span class="fineme">throughout the iframe...
给定一个带有<span class="fineme">整个 iframe 的 iframe ...
Is it possible to add an event listener with jQuery to trigger an ALERT anytime the user moves their mouse over .fineme in the iframe, from the top/parent window?
是否可以使用 jQuery 添加事件侦听器以在用户从顶部/父窗口将鼠标移到 iframe 中的 .fineme 上时触发警报?
回答by Sean Hogan
See http://api.jquery.com/contents/for accessing content document of an iframe.
请参阅http://api.jquery.com/contents/以访问 iframe 的内容文档。
A solution to your question might be:
您的问题的解决方案可能是:
$("iframe#name").contents().find(".fineme").bind("mouseover", function() { alert("Found me"); });
回答by Matthew Manela
Yea, It seems that by default if you run a selector from the parent window it won't find elements inside the iframe. However, you can explicitly give jQuery the context in order to look inside the iframe.
是的,默认情况下,如果您从父窗口运行选择器,它似乎不会在 iframe 内找到元素。但是,您可以明确地为 jQuery 提供上下文以查看 iframe 内部。
One way to do this would be:
一种方法是:
var iframe = $("#someIframeId");
$(".fineme",iframe.get(0).contentDocument).mouseover(function(){alert('hi')});
NOTE:This will only work if both the parent site and the IFrame are on the same domain. For more information about this see: http://madskristensen.net/post/Iframe-cross-domain-JavaScript-calls.aspx
注意:这仅在父站点和 IFrame 位于同一域中时才有效。有关这方面的更多信息,请参见:http: //madskristensen.net/post/Iframe-cross-domain-JavaScript-calls.aspx
回答by LukeSideris
I had a similar problem and found a solution that works for me. Try this:
我遇到了类似的问题,并找到了适合我的解决方案。试试这个:
document.getElementById('iframe_id').contentWindow.$('.fineme').on( ... )
It works for any jquery functions, but listens for events on the iFrame dom's jQuery.
它适用于任何 jquery 函数,但侦听 iFrame dom 的 jQuery 上的事件。

