繁体   English   中英

JavaScript在特定时间段内显示数组元素

[英]JavaScript display array elements within certain time period

我对JavaScript比较陌生,正在从事一些练习。 我正在尝试创建一个练习,在该练习中,每个页面每次加载5秒钟时,一次就会显示客户评论。 每个评论都是一个对象数组元素。 因此,我试图找出如何遍历对象数组并显示每个元素5秒的方法。 我已经做了一些研究,这就是我所能想到的。 我什至靠近吗?

<script>
  var customerReviews = {
    "Denise Wilson": [
      "I absolutely love this restaurant! The food is amazing. The atmosphere
      is so welcoming."
    ],
    "Russell Brown": [
      "Enid's restaurant is the best place in town. Great food, nice staff
      and
      very clean spot."
    ],
    "Dana Evans": [
      "Came here for the 1st time and must say I'm impressed. Will definitely
      be coming back. Enjoyed myself."
    ],
    "Bilal Scott": [
      "Been coming here since I was a child. Loved it then and still love it
      now. The best!"
    ]
  };

  function showCustomerReviews(){
    for (i = 0; i < userWord.length; i++){
      setTimeout(function () { .show(customerReviews[i]); }, 5000);
    }
  }
</script>

HTML

<body onload="showCustomerReviews()">
  <div id="reviewsPage">
    <h2>Check out Enid's Restaurant Customer Reviews below</h2>
    <div id="reviewsBox">
      <p>Enid's Customer Reviews</p>
      <p id="displayReviews"></p>
    </div>
  </div>

通常,如果您希望以固定的时间间隔进行操作,则setIntervalsetTimeout的更好选择。 您可以启动它并使其运行,而不会出现与for循环中的超时相关的问题。

在这里,我对您的代码进行了一些更改,以使customerReviews成为包含评论对象的真实数组,该评论对象具有评论者的姓名和评论本身作为属性。 然后,只需运行setInterval()并递增索引即可。 为了使其循环,需要使用索引mod % array.length

如果要停止它,可以使用clearInterval

 var customerReviews = [ { name: "Denise Wilson", review:"I absolutely love this restaurant! The food is amazing. The atmosphere is so welcoming." }, { name: "Russell Brown", review: "Enid's restaurant is the best place in town. Great food, nice staff and very clean spot." }, { name: "Dana Evans", review: "Came here for the 1st time and must say I'm impressed. Will definitely be coming back. Enjoyed myself." }, { name: "Bilal Scott", review: "Been coming here since I was a child. Loved it then and still love it now. The best!" } ]; function showCustomerReviews(){ let i = 0 // set initial review let review = customerReviews[i++ % customerReviews.length] $('#displayReviews').text(review.name + ": " + review.review); // change it on interval setInterval(function(){ let review = customerReviews[i++ % customerReviews.length] $('#displayReviews').text(review.name + ": " + review.review); }, 5000); } showCustomerReviews() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="reviewsPage"> <h2>Check out Enid's Restaurant Customer Reviews below</h2> <div id="reviewsBox"> <p>Enid's Customer Reviews</p> <p id="displayReviews"></p> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM