代码之家  ›  专栏  ›  技术社区  ›  faressoft

如何向iframe中的p元素添加click事件(使用jQuery)

  •  9
  • faressoft  · 技术社区  · 14 年前

    如何将单击事件添加到 <p> iframe中的元素(使用jQuery)

    <iframe frameborder="0" id="oframe" src="iframe.html" width="100%" name="oframe">
    
    4 回复  |  直到 14 年前
        1
  •  11
  •   jerone    14 年前
        2
  •  1
  •   supremebeing7 RobertPitt    9 年前

    最好的办法是调用iframe,只要它是域的一部分。

    <html>
        <head>
            <script>
                window.MyMethod = function()
                {
                    $('p').click();
                }
            </script>
        </head>
        <body></body>
    </html>
    

    document.getElementById('targetFrame').contentWindow.MyMethod();
    

    调用那个函数。

    window.frames .

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

    还有javascript

    child_frame = window.frames['myIframe'].document;
    $('p',child_frame).click(function(){
        alert('This click as bound via the parent frame')
    });
    

    那应该行得通。

        3
  •  0
  •   RoToRa    14 年前

    通过将IFrame文档的引用作为jQuery的第二个参数,即上下文:

    jQuery("p", document.frames["oframe"].document).click(...);
    
        4
  •  0
  •   Sachin Singh    9 年前

    var iframe = document.getElementById("iframe");
    var iframeDoc = iframe.contentDocument || iframe.contentWindow;
    // Get HTML element
    var iframeHtml = iframeDoc.getElementsByTagName("html")[0];
    

    现在可以使用这个html元素选择任何元素

    iframeHtml.getElementById("someElement");
    

        5
  •  0
  •   yenren    4 年前

    想添加这个,作为一个完整的复制粘贴解决方案(在Firefox和Chrome上工作)。有时很容易忘记在文档之后调用事件,因此iframe已完全加载:

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