获取iframe onload元素

时间:2016-03-18 16:24:48

标签: javascript jquery iframe youtube

我有<iframe src="myYouTubeLink" onload="test">

如何将iFrame src 导入&#34;测试&#34;功能

&#13;
&#13;
function test() {
  // obtain the iframe src 
  var code = false;
  if (code)
    alert('code: ' + code);
}
&#13;
<h2>this is the video</h2>
<div style="width:150px">
  <div class="video-container">
    <iframe id="test456" src="https://www.youtube.com/embed/amDMGIyyrlw" onload="test()">
    </iframe>
  </div>
</div>
&#13;
&#13;
&#13;

以下是 codepen ...

PS。

我需要从测试中获取调用者,然后调用caller.src ...因为我将为多个元素使用相同的函数。

2 个答案:

答案 0 :(得分:2)

由于问题中有一个jQuery标记,这里有一个jQuery答案。当然,您需要在页面中引用jQuery库才能实现此目的。

HTML:

<h2>this is the video</h2>
<div style="width:150px">
    <div class="video-container">
        <!-- note: removed the onload definition from the iframe element -->
        <iframe id="test456" src="https://www.youtube.com/embed/amDMGIyyrlw"></iframe>
    </div>
</div>

JS:

//jquery document ready event -- fires when document is first loaded
$('document').ready(function(){

    //attach an onload event handler to each iframe     
    //(can change the selector to select specific iframes)
    $('iframe').load(function(e){

        //the jquery event will automatically have a target 
        //property that is set to the element that fired the event
        //you can pull the src property from that
        alert(e.target.src);

        //pass the target element to a test function
        test(e.target);
    });
});

function test(iframe){
    //check src or other properties to see if the element passes or fails the test
    //example: testing that the value is not the empty string
    //but any check can be done here depending on requirements
    if(iframe.src != ""){

        //check any properties of the iframe

        //pass or fail

        //perform other actions as needed
    }
}

答案 1 :(得分:1)

您可以选择参考吗?

<h2>this is the video</h2>
<div style="width:150px">
  <div class="video-container">
    <iframe id="test456" src="https://www.youtube.com/embed/amDMGIyyrlw" onload="test(this)"></iframe>
  </div>
</div>

JS:

function test(caller){
  // obtain the iframe src 
  // then youtube embed code
    alert(caller.id);
  var code = false;
  if (code)
    alert('code: ' + code);
}