how to refer iframe within iframe

2020-04-20 21:52发布

问题:

I want to refer iframe which is inside another iframe

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="playButton">Play</div>
<div class="flex-active-slide">
<iframe src=""> <!--But refering this-->
  #document
   <html>
      <body>
        <iframe src=""><!--want to refer this iframe -->
          #document
           <html>
              <body>

              </body>
           </html>
        </iframe>
      </body>
   </html>
 <iframe>
   </div>

  jQuery(document).ready(function($){
  $(".playButton").on('click',function(){
      $(".flex-active-slide iframe")[0].src += "&autoplay=1";
    });
  });

回答1:

Use contents() to get inside first frame window once it has loaded:

$('iframe').on('load', function(){
  var $secondFrame = $(this).contents().find('iframe');
      $secondFrame.attr('src', someUrl)    
})


回答2:

Consider this:

<div class="flex-active-slide">
<iframe class="i1" src=""> <!--But refering this-->
  #document
   <html>
      <body>
        <iframe class="i2" src=""><!--want to refer this iframe -->
          #document
           <html>
              <body>

              </body>
           </html>
        </iframe>
      </body>
   </html>
 <iframe>
   </div>

You can access iframe with class "i2" as:

var l1 = $(".flex-active-slide .i1")[0];
$(l1.contentDocument).find("iframe.i2");