如何一次显示一个元素?

时间:2018-09-13 17:01:23

标签: javascript jquery html json

我正在尝试一次显示一个元素。它们来自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
    }

  ]
}

JavaScript

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();

任何帮助,不胜感激。

2 个答案:

答案 0 :(得分:3)

因为您有不同的毫秒值,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);

答案 1 :(得分:2)

我建议使用超时对数组执行递归循环。

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();