簡體   English   中英

如何一次顯示一個元素?

[英]How can I display elements one at a time?

我正在嘗試一次顯示一個元素。 它們來自JSON文件。 我正在使用JQuery和setInterval。 但圖像要改變基於文件的“毫秒

我究竟做錯了什么? 我的實現基於一次僅顯示一個數組項(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); 

我建議使用超時對數組執行遞歸循環。

 function DisplayMessages() { $.getJSON(screenSettingsUrl, (data) => { var i = 0; if (data != null) { function displayNextItem () { //show the current image divName.css("background-image", "url(./media/" + data.PlaylistItems[i].FileName + ")"); divName.css("background-repeat", "no-repeat"); //advance i to the next image, or back to 0 if it reaches the end //of the array i = ++i % data.PlaylistItems.length; //start the loop for the next element, with it's timeout setTimeout(displayNextImage, data.PlaylistItems[i].Milliseconds); } //start the loop on the first element, with it's timeout setTimeout(displayNextImage, data.PlaylistItems[i].Milliseconds); } }); } DisplayMessages(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM