开发者

Adding an Event Listener to Items in an iFrame?

Given an iframe with <span class="fineme"> throughout the 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开发者_开发知识库?


See http://api.jquery.com/contents/ for accessing content document of an iframe.

A solution to your question might be:

$("iframe#name").contents().find(".fineme").bind("mouseover", function() { alert("Found me"); });


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.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜