小编Edw*_*ien的帖子

使用JavaScript无法更改iframe src

我正在尝试从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);" />
Run Code Online (Sandbox Code Playgroud)

这是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  
    }  
} …
Run Code Online (Sandbox Code Playgroud)

javascript youtube iframe

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

iframe ×1

javascript ×1

youtube ×1