Javascript 获取iframe onload元素
我有Javascript 获取iframe onload元素,javascript,jquery,iframe,youtube,Javascript,Jquery,Iframe,Youtube,我有 如何进入“测试”功能的iFramesrc 功能测试(){ //获取iframe src var代码=假; if(代码) 警报(“代码:”+代码); } 这是视频 参考资料是您的选择吗 <h2>this is the video</h2> <div style="width:150px"> <div class="video-container"> <iframe id="test456" src="https://www.
如何进入“测试”功能的iFramesrc
功能测试(){
//获取iframe src
var代码=假;
if(代码)
警报(“代码:”+代码);
}
这是视频
参考资料是您的选择吗
<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>
因为问题中有一个jQuery标记,下面是jQuery的答案。当然,您需要在页面中引用jQuery库,才能使其正常工作 HTML:
用于从DOM标记中删除js函数调用的+1。那更好。假设我有100个视频的动态负载。其中50人应该通过测试,另外50人不应该。。。因此,我需要对每个视频单独说明它是
test()
还是不…更新了代码示例,以显示如何将目标对象(表示iframe)传递给您希望执行其他逻辑的任何函数。
function test(caller){
// obtain the iframe src
// then youtube embed code
alert(caller.id);
var code = false;
if (code)
alert('code: ' + code);
}
<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>
//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
}
}