使用JavaScript无法更改iframe src

时间:2021-12-03 14:09:04

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中,在单击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!

谢谢你的帮助!

1 个解决方案

#1


4  

src is 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 src there is no need to refresh the iframe, as setting the src will 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 src of an iframe to itself to refresh the iframe).

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

#1


4  

src is 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 src there is no need to refresh the iframe, as setting the src will 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 src of an iframe to itself to refresh the iframe).

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