如何使用jQuery或javascript访问iframe的内容 [英] How to access the contents of an iframe using jQuery or javascript

查看:105
本文介绍了如何使用jQuery或javascript访问iframe的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载页面的iframe,当点击一个按钮时,该页面会加载包含链接的动态内容。我需要将所有这些链接的目标从 _blank 更改为 _self - 但我完全坚持如何每次在iframe中加载新内容时都会运行代码。我尝试了很多选项,最新的方法是将一个点击功能添加到iframe作为运行代码的触发器:

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');
  });
});

在内容加载到iframe后,如何查找动态生成的内容并更改链接目标?没有同源政策问题,因为iframe中的页面位于同一个域中。

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.

谢谢。

推荐答案

使用javaScript获取iframe的DOM,如下所示:

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

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

注意:如果您的框架使用名称而不是 id class 你遵循上面的规则来获得你的框架的DOM

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

将此更改为jquery对象

change this to jquery object

var elem=$(doc);

现在绑定 elem 上的点击事件在你的问题中的代码中做了

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');
 });

});

这篇关于如何使用jQuery或javascript访问iframe的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆