我有一个列表,我正在尝试迭代以将每个 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>
最佳答案
您可以尝试使用相同的循环索引来访问两个数组中的数据。
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/