Javascript 循环执行JS数组onclick并将值写入DOM
因此,我得到了这个JavaScript数组,其中包含50个YouTube视频id和一个while循环,该循环将前两个视频写入DOM。这段代码是用PHP打印的,以防您对反斜杠感到疑惑Javascript 循环执行JS数组onclick并将值写入DOM,javascript,jquery,Javascript,Jquery,因此,我得到了这个JavaScript数组,其中包含50个YouTube视频id和一个while循环,该循环将前两个视频写入DOM。这段代码是用PHP打印的,以防您对反斜杠感到疑惑 <script type="text/javascript"> var videoArr=["id1", "id2", etc.]; var i = 0; while (i<2) { document.write(\'<iframe width="400" height="225" src="
<script type="text/javascript">
var videoArr=["id1", "id2", etc.];
var i = 0;
while (i<2) {
document.write(\'<iframe width="400" height="225" src="http://www.youtube.com/embed/ \'+videoArr[i]+\'?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe>\');
i++;
}
</script>
var videoArr=[“id1”、“id2”等];
var i=0;
虽然(i您已经在全局范围内声明了var i
,但是现在您只需要增加或减少i
并将其附加到DOM中的函数,而不是document.write()
当DOM已经加载时,您应该将它们附加到
中
您好,谢谢。一次添加两个视频非常重要。如何在每次单击时调用函数两次?同样,使用此代码,视频似乎只有在我单击按钮时才会出现。数组中的前两个视频必须从一开始就存在。@AzzyDude看到我添加的示例单击事件。谢谢,这是可行的,但此方法不是真实的非常合适。加载DOM时需要显示前两个视频,而“上一个”和“下一个”按钮用于将当前两个视频与阵列中的下两个视频交换。您的代码只是在已经存在的视频旁边添加两个新视频。@AzzyDude您的问题没有提到交换,它说您需要将下两个视频写入DOM.使用类似于$('body')的内容删除现有的iframe。删除('iframe');
如果原始视频没有消失,为什么我需要一个“上一个”和“下一个”按钮?我只需要一个按钮,上面写着“显示两个以上的视频”。
// i is at global scope
var i = 0;
function previousVideo() {
// Only if you're not already at the beginning of the array
if (i > 0) {
i--;
// You tagged this jQuery, so here's the simpler jQuery solution
appendVideo(i);
}
}
function nextVideo() {
// Only if you're not already at the end of the array
if (i < videoArr.length - 1) {
i++;
appendVideo(i);
}
}
// Appends a new iframe to the <body>
function appendVideo(i) {
$("body").append('<iframe width="400" height="225" src="http://www.youtube.com/embed/' + videoArr[i] + '?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe>');
}
$('#yourbutton').click(function() {
// Get rid of the old ones
$('body').remove('iframe');
// And write two new ones.
previousVideo();
previousVideo();
});