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

2019-02-09 04:55发布

问题:

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">

回答1:

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



回答2:

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.



回答3:

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(...);


回答4:

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.