我正在尝试一次显示一个元素。它们来自JSON文件。我正在使用JQuery和setInterval。但是图像应根据文件的“毫秒”更改
我究竟做错了什么?
我的实现基于Only display one array item at a time (Javascript)
JSON文件
{
"Name": "2",
"PlaylistItems": [
{
"FileName": "ad1.png",
"Duration": "00:00:23",
"Milliseconds": 1300.0
},
{
"FileName": "ad2.jpg",
"Duration": "00:00:00",
"Milliseconds": 25000.0
},
{
"FileName": "ad3.png",
"Duration": "00:00:00",
"Milliseconds": 5400.0
}
]
}
Java脚本
function DisplayMessages() {
$.getJSON(screenSettingsUrl, (data) => {
if (data != null) {
var i = 0;
setInterval(() => {
divName.css("background-image", "url(./media/" + data.PlaylistItems[i].FileName + ")");
divName.css("background-repeat", "no-repeat");
i++;
if(i == data.PlaylistItems.length) i = 0;
}, data.PlaylistItems[i].Milliseconds);
}
});
}
DisplayMessages();
任何帮助,不胜感激。
最佳答案
因为您具有不同的毫秒值,所以setInterval不是最佳选择。在这种情况下,我建议使用setTimeout和递归方法。
var data = {
"Name": "2",
"PlaylistItems": [
{
"FileName": "ad1.png",
"Duration": "00:00:23",
"Milliseconds": 1300.0
},
{
"FileName": "ad2.jpg",
"Duration": "00:00:00",
"Milliseconds": 2500.0
},
{
"FileName": "ad3.png",
"Duration": "00:00:00",
"Milliseconds": 5400.0
}
]
};
function DisplayMessages(i) {
setTimeout(() => {
console.log(data.PlaylistItems[i].FileName);
i++;
if (i < data.PlaylistItems.length) DisplayMessages(i);
}, data.PlaylistItems[i].Milliseconds);
}
DisplayMessages(0);