【问题标题】:jQuery show() not working within iFramejQuery show() 在 iF​​rame 中不起作用
【发布时间】:2013-12-13 07:14:00
【问题描述】:

我正在尝试做一些非常简单的事情,但它只是不起作用。我试图在 iFrame 内的页面加载时显示 div。如果我查看 html 页面本身,则会显示 div。有谁知道 iFrame 中的 jQuery 可能存在的任何问题?如果我执行 alert() 它也会显示。

我的基本代码如下:

对 iFrame 的引用

     <li>
         <iframe src="/Markup/Page2.htm" marginheight="0" marginwidth="0" frameborder="0"></iframe>
     </li>

Page2.htm 中的 HTML

<div class="Container">
    <p class="ShowThis" style="display:none;">Show me on load</p>
</div>

Page2.htm 中的 jQuery

$(document).ready(function () {
    $('.ShowThis').show();
});

【问题讨论】:

    标签: jquery html iframe


    【解决方案1】:

    您需要获取对 iframe 的引用并访问其文档,然后以 iframe 文档作为上下文搜索 DOM。

    Live demo here (click).

    这是通用的 JavaScript:

    $iframe = $('#myIframe'); 
    $iframeElem = $('#myIframeElem', $iframe.contents());
    

    以及特定于您使用的代码:

    标记:

    <iframe id="myIframe"></iframe>
    

    在 page2.html 中:

    <div class="Container">
      <p class="showThis" style="display:none;">Show me!</p>
    </div>
    

    JavaScript:

    iframe = $('#myIframe');
    
    $iframe.load(function() {
      $iframeElem = $('.showThis', $iframe.contents());
      $iframeElem.show();
    });
    
    $iframe.attr('src', 'page2.html');
    

    【讨论】:

    • .contents(); 呢?
    • 谢谢!很棒的解决方案。
    【解决方案2】:

    我认为这段代码的问题在于您没有正确引用 Iframe 的元素。应通过引用 Iframe 来访问 Iframe 中的容器类。

       var iframe=$("#Iframe");
    $("#Iframe").load(function(e) {
    
    
            $(iframe.contentWindow.document.body).find('.Container').bind('event',function( event ){
    
             //write code here
    
            });
        });
    

    【讨论】:

    • 请不要忘记为您的 iframe 提供正确的 ID。在我的情况下,ID 是“Iframe”
    猜你喜欢
    • 2015-10-03
    • 2019-05-12
    • 2012-05-02
    • 2018-02-26
    • 2011-11-08
    • 2010-10-21
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多