How to add a click event to p elements in iframe (

2019-02-09 04:47发布

How to add a click event to <p> elements in iframe (using jQuery)

<iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">

4条回答
Luminary・发光体
2楼-- · 2019-02-09 05:29

By giving a reference to the IFrame document as the second parameter to jQuery, which is the context:

jQuery("p", document.frames["oframe"].document).click(...);
查看更多
何必那么认真
3楼-- · 2019-02-09 05:31

To access any element from within an iframe, a simple JavaScript approach is as follows:

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

iframeHtml.getElementById("someElement");

Now, you can bind any event you want to this element. Hope this helps. Sorry for incorrect English.

查看更多
甜甜的少女心
4楼-- · 2019-02-09 05:39

Your best best bet is to invoke the iframe AS LONG AS it's part of your domain.

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.

<iframe name="myIframe" src="iframe.html"/>

and the 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.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-09 05:43

There's a special jQuery function that does that: .contents(). See the example for how it's works.

查看更多
登录 后发表回答