循环多维数组并以html格式显示数据

时间:2015-01-23 02:05:47

标签: javascript jquery html arrays multidimensional-array

我正在尝试循环数组并显示数据,有点像图像滑块。我希望它使用'0'然后在3秒后显示'1'等等,然后循环回到开始。

    var people = {
   0: {
     'name': '<span class="name">Name</span>',
     'desc': '<span>Some text about this person.</span>',
     'imgSrc': "<div class='team-img></div>"
   },

   1: {
     'name': '<span class="name">Name</span>',
     'desc': '<span>Some text about this person.</span>',
     'imgSrc': "<div class='team-img></div>"
    },
};

$(document).ready(function() {

    setInterval(function() {
    $(".name").replaceWith(array[i]['name']);
        $("article").replaceWith(array[i]['desc']);
        $(".team-img").replaceWith(array[i]['imgSrc']);
    }, 3000)

});

1 个答案:

答案 0 :(得分:0)

使用数组而不是对象。然后,您可以将ipeople.length进行比较,以了解您应该循环播放。

你也有一堆错误。您正在使用article替换span,因此下一次无法找到article。您使用array[i]代替people[i]

&#13;
&#13;
var people = [
   {
    'name': '<span class="name">Name 1</span>',
    'desc': '<article>Some text about this Person 1.</article>',
    'imgSrc': "<div class='team-img'>Image 1</div>"
   },

   {
    'name': '<span class="name">Name 2</span>',
    'desc': '<article>Some text about that person 2.</article>',
    'imgSrc': "<div class='team-img'>Image 2</div>"
   }
];


$(document).ready(function() {
  var i = 0;

  setInterval(function() {
    $(".name").replaceWith(people[i].name);
    $("article").replaceWith(people[i].desc);
    $(".team-img").replaceWith(people[i].imgSrc);
    i = (i+1) % people.length;
  }, 3000)

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="name">No name yet</span>
<br>
<article>No article</article>
<div class="team-img">No image</div>
&#13;
&#13;
&#13;