【问题标题】:why does this code (jquery each.) stops after 1st?为什么这段代码(每个jquery。)在第一次之后停止?
【发布时间】:2017-01-11 17:01:38
【问题描述】:

我的网站顶部有一个名为通知的 div。 我想循环浏览一个文本数组,并每 30 秒在该 div 中一个接一个地显示每个值。

我写的下面的代码不起作用,我已经尝试了好几次,但没有任何效果。

var my_array = ["first text", "second text", "third text"];

jQuery.each(my_array, function(index, value) {
    jQuery('.notifications').replaceWith(value).delay(500);
});

【问题讨论】:

  • .delay() 暂停动画。 .replaceWith() 不是动画。
  • 引用的帖子不使用 each() 循环遍历数组...所以这不是回答我的问题的有效参考。
  • 你研究过吗?有lotslots 关于做你需要做的事情的问题
  • @Ryan 副本解释了您的代码有什么问题,并为您尝试做的事情提供了替代解决方案。 .each() 与问题无关。
  • 即使我删除了延迟部分,它仍然会在第一个部分停止,所以我不明白如果 .each 不循环遍历数组中的每个元素,它如何不是问题的一部分。跨度>

标签: jquery


【解决方案1】:

delay() 方法用于在动画队列中提供延迟,因此您不能将它与replaceWith() 方法一起使用。其次,replaceWith() 将用 DOM 树中的新元素替换整个元素,因此在第二次迭代中,jQuery('.notifications') 不会选择任何内容,因为该元素已经被替换。

要使其正常工作,请使用setInterval 方法,而不是替换整个元素,只需使用text() 方法更新元素的内容。

var my_array = ["first text", "second text", "third text"];

// variable for counting
var i = 0;

// initialize interval and cache the return id
// to clear the interval later
var inter = setInterval(change, 500);
// call the function to execute initially
change();

function change() {
  // update the content
  jQuery('.notifications').text(my_array[i++]);
  // check count reache the length of array
  if (i == my_array.length)
  // if reached length of array then clear the interval
    clearInterval(inter);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="notifications"></span>

【讨论】:

    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多