简体   繁体   English

JQuery在Iframe中查找元素(通过其文本)并向其添加.click函数

[英]JQuery finding an element within Iframe (by its text) and adding .click function to it

I have a webpage (A) and I am embedding (A) to my mainpage (B) using iframe. 我有一个网页(A),我使用iframe将(A)嵌入到我的主页(B)。 This (A) contains a link which closes the browser window: 这个(A)包含一个关闭浏览器窗口的链接:

<a href="" onclick="window.opener = window;
    window.close();
    return false;">Close The Page</a>

Since I embedd (A), the close ability in (A) is no more functional. 由于我嵌入(A),(A)中的紧密能力不再具有功能性。 What I need to do is, when this link is clicked from (B), I want to hide my iframe, in other words make it look like closing. 我需要做的是,当从(B)点击此链接时,我想要隐藏我的iframe,换句话说,让它看起来像关闭。 So I have to reach that link in the iframe and understand if it is clicked or not (B)? 所以我必须在iframe中找到该链接并了解它是否被点击(B)?

Help please. 请帮忙。

Thanks 谢谢

I'm thinking the following will work. 我想以下是可行的。 We're basically performing a "find" on the contents of your iframe. 我们基本上对您的iframe内容执行“查找”。 Once we find the link we want, we bind an event to it that will close the proper iframe in the parent document. 找到我们想要的链接后,我们将一个事件绑定到它,它将关闭父文档中的正确iframe。 Note that your iframe must be on the same domain as your parent page, or you will not be able to access its elements. 请注意,您的iframe必须与您的父网页位于同一个域中,否则您将无法访问其元素。 Additionally, I added a class to the link to make it easier to selection. 另外,我在链接中添加了一个类,以便于选择。 I suggest you also do this. 我建议你也这样做。

$("#iframeID").contents().find("a.closeWindow").bind("click", function(){
  $("#iframeID", top.document).hide();
});

If you absolutely need to base the binding on the text of the link, you'll have to cycle through the links to find the proper one: 如果您绝对需要将绑定基于链接的文本,则必须循环访问链接以找到正确的链接:

$("a", $("#iframeID").contents()).each(function(){
  if ($(this).text() == "Close The Page") {
    $(this).bind("click", function() { 
      $("#iframeID", top.document).hide(); 
    });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM