[英]How to add a click event to p elements in iframe (using jQuery)
如何向 iframe 中的<p>
元素添加点击事件(使用 jQuery)
<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">
There's a special jQuery function that does that: .contents()
.有一个特殊的 jQuery 函数可以做到这一点:
.contents()
。 See the example for how it's works.请参阅示例以了解其工作原理。
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。
<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.那应该可以正常工作。
Wanted to add this, as a complete, copy-paste solution (works on Firefox and Chrome).想要添加这个,作为一个完整的复制粘贴解决方案(适用于 Firefox 和 Chrome)。 Sometimes it is easy to miss to remember to call the event after the document, and so the iframe, is fully loaded:
有时很容易忘记在文档之后调用事件,因此 iframe 已完全加载:
$('#iframe').on('load', function() {
$('#iframe').contents().find('#div-in-iframe').click(function() {
// ...
});
});
The iframe must be on the same domain for this to work. iframe 必须在同一个域中才能工作。
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.
抱歉英语不正确。
通过将 IFrame 文档的引用作为 jQuery 的第二个参数,即上下文:
jQuery("p", document.frames["oframe"].document).click(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.