如何在清单循环中使用.each()?

时间:2019-04-14 03:32:55

标签: javascript jquery html arrays django

我有一个列表要遍历,以将每个div更改为自己的歌曲。 JSON简化了我的列表,因为数据来自Django查询集。我的问题是我不知道如何继续 下一个对象,而无需在循环内重复相同的对象。

我曾尝试过设置变量以阻止它或无法成功播放下一首歌曲。

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

2 个答案:

答案 0 :(得分:1)

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

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>");
});

答案 1 :(得分:1)

$("h1[id]").each(function(index){
            var next_song = [];
            var data = [{"song":{"file":"music/the_unlighteds_2.mp3"}},{"song":{"file":"music/the_unlighted_6_32.mp3"}}]
            console.log(data);
            for (var i in data) {

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


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

});

我从未使用过jquery,但是根据您的需要对其进行了描述。你可以尝试我的写作方式