我开始自学javascript。我想我会尝试制作一个在提供 URL 时嵌入 youtube 视频的脚本。当我创建 iframe 元素、设置属性并将其作为子元素附加到 div 时,谁能帮我理解我做错了什么?我正在使用 JSFiddle,当我检查元素时,似乎没有将标签添加到 div 中。谢谢!
编辑:这是我的 jsfiddle 链接:http: //jsfiddle.net/86W8N/2/
<p>Click the button to call function</p>
YoutubeURL: <input id="url" type="text">
<button onclick="myFunction()">Try it</button>
<div id="video_div">
</div>
<script>
function myFunction() {
var urlValue = document.getElementById("url").value;
var videoID = urlValue.substring(urlValue.indexOf('=') + 1);
var video = document.createElement("iframe");
video.setAttribute(title, "Test");
video.setAttribute(width, "440");
video.setAttribute(height, "390");
video.setAttribute(src, "http://www.youtube.com/embed/" + videoID);
video.setAttribute(frameborder, "0");
var div_element = document.getElementById("video_div");
div_element.appendChild(video);
}
</script>
原文由 user3382426 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码将停止执行,抛出
title is not defined
异常在
setAttribute(title, ...)
你正在使用title
好像它是一个名为 title 的变量,但它不存在。您想改为传递 字符串值"title"
:…其他属性也一样…
自从您使用 JSFiddle 以来,还有一些提示: