javascript - 如何在 for 循环内使用 .each() 和列表?

标签 javascript jquery html arrays django

我有一个列表,我正在尝试迭代以将每个 div 更改为自己的歌曲。我的列表通过 JSON 进行了简化,因为数据来自 Django 查询集。我的问题是我不知道如何继续 下一个对象,而不让它在循环内重复相同的对象。

我尝试设置变量 outisde 来停止它或转到下一首歌曲,但没有成功。

The Json as data variable:  [{"song":{"file":"music/the_unlighteds_2.mp3"}},{"song":{"file":"music/the_unlighted_6_32.mp3"}}]
Script code:

 <script>



        $("h1[id]").each(function(){

            var next_song = "";
            var data = [{{ chap_song|safe }}]
            console.log(data);
            for (var i in data) {

            var next_song = JSON.stringify(data[i].song.file);


            }
            console.log(next_song);
            if(this.id==='scroll-to')$(this).html("<audio controls autoplay> <source src=https://theunlighted.io/media/"+next_song.replace(/\"/g, "")+ " type=\"audio/wav\"></audio>");

});


 </script>

My result ends up like so

最佳答案

您可以尝试使用相同的循环索引来访问两个数组中的数据。

var data = [{{ chap_song|safe }}];
$("h1[id]").each(function(i){ // i is the index of the current h1
  var song = data[i]; // so we want the corresponding song
  $(this).html("<audio controls autoplay> <source src=https://theunlighted.io/media/"+song.file.replace(/\"/g, "")+ " type=\"audio/wav\"></audio>");
});

关于javascript - 如何在 for 循环内使用 .each() 和列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671748/

相关文章:

javascript - 悬停时更改底部边框的颜色

html - 响应式幻灯片 - 调整大小时与另一个 div 重叠

jquery - 如何将类添加到幻灯片中的当前图像?

javascript - 无法将 Google 地理编码数据移至 Django 表单

javascript - jquery 将类添加到最近的父级

HTML flex 替代品

javascript - 每次点击时旋转元素

javascript - 更改 React 中所需的输入消息

javascript - HTML 多头

javascript - 如何禁用 Downloadify