我对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>
答案 0 :(得分:1)
通常,如果您希望以固定的时间间隔进行操作,那么setInterval
是setTimeout
的更好选择。您可以启动它并使其运行,而不会出现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>