我正在尝试并且没有为我的用户编写一个插入式YouTube嵌入式播放器,因此他们只需更改一行即可更改页面上的所有YouTube播放器。我把它放到我的页面中,但没有发生任何事情。
<script>
// Replace line below with video id(s), e.g. ["dQw4w9WgXcQ"] or ["dQw4w9WgXcQ","b1WWpKEPdT4"]
var ids = ["dQw4w9WgXcQ","b1WWpKEPdT4"];
//
//
var idsAmount = ids.length;
for (var i in idsAmount) {
document.write("<iframe src=\"https://www.youtube.com/embed/" + ids[i] + "?modestbranding=1&rel=0&autoplay=1\" /> <br />");
};
</script>
控制台中没有错误。知道为什么没有发生的事吗?
修改:这是我的最终工作代码:
<script>
// Replace line below with video id(s), e.g. ["dQw4w9WgXcQ"] or ["dQw4w9WgXcQ","b1WWpKEPdT4"]
var ids = ["dQw4w9WgXcQ","b1WWpKEPdT4"];
//
if (ids.length == 1) {
document.write("<iframe width=\"640px\" height=\"360px\" src=\"https://www.youtube.com/embed/" + ids + "?modestbranding=1&rel=0&autoplay=1\" frameborder=\"0\" allowfullscreen></iframe>");
document.write("<br />");
}
else {
for (var i = 0; i < ids.length; i++) {
document.write("<iframe width=\"640px\" height=\"360px\" src=\"https://www.youtube.com/embed/" + ids[i] + "?modestbranding=1&rel=0\" frameborder=\"0\" allowfullscreen></iframe>");
document.write("<br /> <br />");
};
};
</script>
答案 0 :(得分:2)
首先,你要转义2个不需要转义的引号(用于连接),同样,循环错误,应该如下:
<script>
// Replace line below with video id(s), e.g. ["dQw4w9WgXcQ"] or ["dQw4w9WgXcQ","b1WWpKEPdT4"]
var ids = ["dQw4w9WgXcQ","b1WWpKEPdT4"];
//
//
for (var i = 0; i < ids.length; i++) {
document.write("<iframe src=\"https://www.youtube.com/embed/" + ids[i] + "?modestbranding=1&rel=0&autoplay=1\" /> <br />");
};
</script>
答案 1 :(得分:1)
我建议只使用document.write()
迭代数组本身,而不是使用for...
和Array.prototype.map()
循环来创建一个HTML节点数组,这些节点本身可以迭代将这些节点附加到文档片段,然后可以将其附加到指定的DOM节点:
// Array of video ids:
var ids = ["dQw4w9WgXcQ", "b1WWpKEPdT4"],
// creating an <iframe> element:
iframeElement = document.createElement('iframe'),
// creating a document fragment:
fragment = document.createDocumentFragment(),
// an unitialised (undefined) variable for later use:
clone,
// iterating over the array of ids, creating a new
// array using Array.prototype.map():
html = ids.map(function(currentID) {
// in the anonymous function the first
// argument (here: 'currentID') is the
// current array-element of the array
// over which we're iterating.
// cloning the <iframe>:
var clone = iframeElement.cloneNode();
// setting the src property of the cloned
// <iframe>:
clone.src = 'https://www.youtube.com/embed/' + currentID + '?modestbranding=1&rel=0&autoplay=0';
// Note that 'autoplay' has been set to
// to '0' on principle.
// returning the modified clone to the array
// we're creating:
return clone;
// iterating over the array returned from
// Array.prototype.map() and appending each
// array-element to the document fragment:
}).forEach(function(iframe) {
fragment.appendChild(iframe);
});
// appending the document fragment to the body element:
document.body.appendChild(fragment);
参考文献: