使用 JavaScript 更改 iframe src 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15506303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:01:58  来源:igfitidea点击:

Changing iframe src with JavaScript not working

javascriptiframeyoutube

提问by Edward Chien

I'm trying to pull a YouTube video id from an img and then pass it into an iframe to play an embedded video. My iframe is inside a div which is invisible until the img is clicked:

我正在尝试从 img 中提取 YouTube 视频 ID,然后将其传递到 iframe 以播放嵌入的视频。我的 iframe 位于一个 div 内,该 div 在单击 img 之前是不可见的:

<div id="testimonialbackground" style="display:none;">  
    <a href="#" onclick="toggledisplay(this);">Click here</a> to close the video  
    <iframe id="testimonialframe" src="" frameborder="0" allowfullscreen></iframe>  
</div>  
<img src="http://img.youtube.com/vi/x-ROeKGEYSk/1.jpg" onclick="toggledisplay(this);" />

And here's the JavaScript. It works fine until this line elem.setAttribute('src', newsrc);, at which point my page freezes up:

这是 JavaScript。它工作正常,直到这一行elem.setAttribute('src', newsrc);,此时我的页面冻结:

function toggledisplay(obj) {  
    var div = document.getElementById('testimonialbackground');  
    var elem = document.getElementById('testimonialframe');  
    if (div.style.display == "block") {  
        div.style.display = "none";  
        elem.setAttribute('src', "");  
    }  
    else {  
        div.style.display = "block";  
        var explosion = obj.src.split("/");  
        var newsrc = "http://www.youtube.com/embed/" + explosion[4] + "?autoplay=1";  
        elem.setAttribute('src', newsrc); // <---- BROKEN LINE RIGHT HERE
        elem.contentWindow.location.reload(); //to refresh the iframe  
    }  
}

Thanks for any help!

谢谢你的帮助!

回答by Ryan

srcis an attribute you can access directly so instead of your line elem.setAttribute('src', newsrc);just use this:

src是一个你可以直接访问的属性,所以不要elem.setAttribute('src', newsrc);使用你的行,只需使用这个:

elem.src = "http://www.youtube.com/embed/" + explosion[4] + "?autoplay=1";

Once you set the srcthere is no need to refresh the iframe, as setting the srcwill do that automatically. See What's the best way to reload / refresh an iframe using JavaScript?for more info on reloading iframes. (Basically it points out that you can set the srcof an iframeto itself to refresh the iframe).

设置后src无需刷新iframe,因为设置src将自动执行此操作。请参阅使用 JavaScript 重新加载/刷新 iframe 的最佳方法是什么?有关重新加载的更多信息iframes。(基本上,它指出,你可以设置srciframe本身刷新iframe)。