【问题标题】:get iframe onload element获取 iframe onload 元素
【发布时间】:2016-03-18 16:24:48
【问题描述】:

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

如何才能将 iFrame src 放入“测试”功能?

function test() {
  // obtain the iframe src 
  var code = false;
  if (code)
    alert('code: ' + code);
}
<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>

这里是 codepen...

附言。

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

【问题讨论】:

    标签: javascript jquery iframe youtube


    【解决方案1】:

    由于问题中有一个 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 用于从 DOM 标记中删除 js 函数调用。这样更好。
    • 想象一下我有 100 个视频的动态负载。其中 50 个应该通过测试,其他 50 个不应该...所以我需要单独对每个视频说是否test()...
    • 更新了代码示例,展示了如何将目标对象(代表 iframe)传递给您希望执行其他逻辑的任何函数。
    【解决方案2】:

    您可以选择参考吗?

    <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);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-19
      • 2017-03-08
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 2018-01-13
      相关资源
      最近更新 更多