开发者

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

开发者 https://www.devze.com 2023-01-15 21:59 出处:网络
How to add a click event to <p> elements in iframe (using jQuery) <iframe frameborder=\"0\" id开发者_Python百科=\"oframe\" src=\"iframe.html\" width=\"100%\" name=\"oframe\">

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

<iframe frameborder="0" id开发者_Python百科="oframe" src="iframe.html" width="100%" name="oframe">


There's a special jQuery function that does that: .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.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.


Wanted to add this, as a complete, copy-paste solution (works on Firefox and Chrome). Sometimes it is easy to miss to remember to call the event after the document, and so the iframe, is fully loaded:

$('#iframe').on('load', function() {
    $('#iframe').contents().find('#div-in-iframe').click(function() {
        // ...
    });
});

The iframe must be on the same domain for this to work.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消