How to access the contents of an iframe using jQuery or javascript

拥有回忆 提交于 2019-12-02 23:02:46

问题


I have an iframe that loads a page which, when a button is clicked, loads dynamic content including links. I need to change the target of all these links from _blank to _self - but I'm completely stuck on how to get the code to run each time the new content is loaded in the iframe. I've tried lots of options, the latest being to add a click function to the iframe as a trigger to run the code:

$("#myFrame").click(function () {
  $('#myFrame').find('a[target="_blank"]').each(function () {
    $(this).attr('target', '_self');
  });
});

How do find the dynamically generated content and change the link targets once the content has finished loading in the iframe? There is no 'same origin policy' issue, as the page in the iframe is on the same domain.

Thanks.


回答1:


use javaScript to get the DOM of your iframe like this:

var doc=window.frames[ "yourFrameName" ].document

NOTE: Use name not id or class of your frame if you are following above rule to get the DOM of your frame

change this to jquery object

var elem=$(doc);

now bind click event on elem as you are doing in code in your question

elem.click(function () {

 elem.find('a[target="_blank"]').each(function () {

  $(this).attr('target', '_self');
 });

});



回答2:


You can use contents() method

Here is an example :

$("#myiframe").contents().find("#myContent")


来源:https://stackoverflow.com/questions/19420767/how-to-access-the-contents-of-an-iframe-using-jquery-or-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!