javascript 如何向 iframe 中的 p 元素添加点击事件(使用 jQuery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3708969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a click event to p elements in iframe (using jQuery)
提问by faressoft
How to add a click event to <p>elements in iframe (using jQuery)
如何向<p>iframe 中的元素添加点击事件(使用 jQuery)
<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">
采纳答案by jerone
There's a special jQuery function that does that: .contents(). See the example for how it's works.
还有,做一个特殊的jQuery函数:.contents()。请参阅示例了解其工作原理。
回答by RobertPitt
Your best best bet is to invoke the iframe AS LONG AS it's part of your domain.
最好的办法是调用 iframe,只要它是您域的一部分。
iframe.html
iframe.html
<html>
<head>
<script>
window.MyMethod = function()
{
$('p').click();
}
</script>
</head>
<body></body>
</html>
And then use
然后使用
document.getElementById('targetFrame').contentWindow.MyMethod();
To invoke that function.
调用该函数。
another way is to access the iframe via window.frames.
另一种方法是通过window.frames.
<iframe name="myIframe" src="iframe.html"/>
and the javascript
和 javascript
child_frame = window.frames['myIframe'].document;
$('p',child_frame).click(function(){
alert('This click as bound via the parent frame')
});
That should work fine.
那应该可以正常工作。
回答by RoToRa
By giving a reference to the IFrame document as the second parameter to jQuery, which is the context:
通过将 IFrame 文档的引用作为 jQuery 的第二个参数,即上下文:
jQuery("p", document.frames["oframe"].document).click(...);
回答by Sachin Singh
To access any element from within an iframe, a simple JavaScript approach is as follows:
要从 iframe 中访问任何元素,一个简单的 JavaScript 方法如下:
var iframe = document.getElementById("iframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow;
// Get HTML element
var iframeHtml = iframeDoc.getElementsByTagName("html")[0];
Now you can select any element using this html element
现在您可以使用此 html 元素选择任何元素
iframeHtml.getElementById("someElement");
Now, you can bind any event you want to this element. Hope this helps. Sorry for incorrect English.
现在,您可以将您想要的任何事件绑定到此元素。希望这可以帮助。抱歉英语不正确。

