应用“onclick"到 iFrame 中的所有元素 [英] Apply "onclick" to all elements in an iFrame

查看:16
本文介绍了应用“onclick"到 iFrame 中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 JavaScript DOM 将 onclick 事件应用到 iframe 内的链接?

How do I use the JavaScript DOM to apply onclick events to links inside of an iframe?

这是我正在尝试但不起作用的方法:

Here's what I'm trying that isn't working:

document.getElementById('myIframe').contentDocument.getElementsByTagName('a').onclick = function();

似乎没有抛出任何错误,并且我可以完全控制 iframe 中的内容.

No errors seem to be thrown, and I have complete control of the stuff in the iframe.

这里有一些代码可以测试,看看我是否至少可以计算出我的 iframe 中有多少 div.

Here is some code to test and see if I can at least count how many div's are in my iframe.

// access body
var docBody = document.getElementsByTagName("body")[0];

// create and load iframe element
var embed_results = document.createElement('iframe');
embed_results.id = "myIframe";
embed_results.setAttribute("src", "http://www.mysite.com/syndication/php/embed.php");

// append to body
docBody.appendChild(embed_results);

// count the divs in iframe and alert   
alert(document.getElementById("myIframe").contentDocument.getElementsByTagName('div').length);

推荐答案

iFrame 可以从不同域的另一个网站获取内容.

It is possible for an iFrame to source content from another website on a different domain.

能够访问其他域上的内容将对用户构成安全漏洞,因此无法通过 Javascript 进行此操作.

Being able to access content on other domains would represent a security vulnerability to the user and so it is not possible to do this via Javascript.

因此,您不能将页面中的事件附加到 iFrame 中的内容.

For this reason, you can not attach events in your page to content within an iFrame.

这篇关于应用“onclick"到 iFrame 中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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