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

Loop multidimensional array and display the data in html

本文关键字:html 格式 显示 数据 数组 循环      更新时间:2023-09-26

我正在尝试循环数组并显示数据,有点像图像滑块。我希望它使用"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)
});

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

你也有一堆错误。您正在用span替换article,因此下次找不到article。而且您使用的是array[i]而不是people[i].

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