JQuery finding an element within Iframe (by its te

2019-04-08 17:47发布

I have a webpage (A) and I am embedding (A) to my mainpage (B) using iframe. This (A) contains a link which closes the browser window:

<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. 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. So I have to reach that link in the iframe and understand if it is clicked or not (B)?

Help please.

Thanks

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-08 18:24

I'm thinking the following will work. We're basically performing a "find" on the contents of your iframe. Once we find the link we want, we bind an event to it that will close the proper iframe in the parent document. Note that your iframe must be on the same domain as your parent page, or you will not be able to access its elements. 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(); 
    });
  }
});
查看更多
登录 后发表回答