问题描述:

I'm trying to do something really simple, but yet its just not working. Im trying to show a div on page load within an iFrame. If I view the html page itself the div shows. does anyone know of any possible issues with jQuery within iFrames? If i do an alert() it also shows.

My basic code below:

Reference to the iFrame

 <li>

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

</li>

HTML inside Page2.htm

<div class="Container">

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

</div>

jQuery inside Page2.htm

$(document).ready(function () {

$('.ShowThis').show();

});

网友答案:

You need to get the reference to the iframe and access its document, then search the DOM with the iframe document as the context.

Live demo here (click).

Here's the generic JavaScript for this:

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

And code specific to your usage:

Markup:

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

In 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');
网友答案:

I think the problem with this code is that you are not properly referencing the elements of the Iframe properly. The container class within the Iframe should be accessed by referencing the Iframe.

   var iframe=$("#Iframe");
$("#Iframe").load(function(e) {


        $(iframe.contentWindow.document.body).find('.Container').bind('event',function( event ){

         //write code here

        });
    });
相关阅读:
Top