如何让IFRAME监听父iframe的click事件并使用父iframe中单击元素的路径

我在同一个域中的html页面中有两个iframe

  

我已经为iframe中的a标签提供了click事件,我从中获取了父iframe中被点击元素的路径

 $('a').click(function(e){ var path = $(this).getPath(); var ahash={ 'path':path }; if (getFrameElement()) window.parent.document.Aaddevent(e, ahash); }); 

我现在想要使用此路径并触发其他iframe中的click事件,以便两个iframe具有相同的页面视图。 我通过以下方式使用父iframe的click事件中的第二个iframe中的路径:

  var iframes= parent.document.getElementsByTagName('iframe'); for (var i= iframes.length; i--;) { var iframe= iframes[i]; if($(iframe)){ if (ahash.path!=undefined) { $(iframe).click(function(e) { $(this).find(ahash.path).trigger('click'); }).click(); $(iframe).unbind('click'); } } } 

我现在面临的问题是我收到了在第二个iframe中触发的点击事件的警报,但它没有加载父iframe的路径并打开与父iframe相同的内容。

我不明白我在做错的地方。 是否有可能按照我的方式来实现它? 如果是这样,任何人都可以建议我为什么会这样,以及我需要做什么,以便其他iframe使用父iframe中的click事件的父iframe的路径打开内容。

你正在做很多循环,如果jQuery会自动为你做。 除非我遗漏了什么。 请参阅我对每行的评论:

 var iframes= parent.document.getElementsByTagName('iframe'); // why not use jQuery? for (var i= iframes.length; i--;) { // why not use jQuery here? var iframe= iframes[i]; if($(iframe)) { // always true - even an empty jQuery object returns true // where does ahash come from? if (ahash.path!=undefined) { // Why not do this check outside the loop? $(iframe).click(function(e) { $(this).find(ahash.path).trigger('click'); // this will do nothing // $(this).find() will be empty - your iframe has no children // you want $(this).contents().find(); }).click(); // why immediately call click and then unbind? $(iframe).unbind('click'); // why not just call the code? } // is this brace in the right spot? // missing brace // missing brace 

我会像这样重写它:

 $("iframe", parent.document).contents().find(ahash.path).click(); 

细分,即:

 $("iframe", parent.document) // get all of the iframes in the parent document .contents() // get the content documents of those frames .find(ahash.path) // find the elements matching the ahash.path in each // of the frames' content documents .click(); // trigger a click on the matching elements in each frame 

这是你想要做的吗? 如果是这样,那么我相信你的问题是你在调用.find()之前没有在你的iframe上调用.contents() .find()

编辑:请注意,您无法通过调用$("a#myLink").click()导航到url$("a#myLink").click() 。 您将不得不操纵location.href 。 但是,在IE和更新版本的FireFox和Opera中,您可以通过直接调用元素的本机DOM方法.click()$("a#myLink")[0].click() 。 由于这是HTML5的一部分,您很快就可以在Chrome中执行此操作。

这是一个演示,显示jQuery的click()方法在链接上的行为: http : //jsfiddle.net/gilly3/C48mv/1/