首页 > 解决方案 > jQuery .each 和 setTimeout 不起作用

问题描述

我正在尝试从活动滑块中获取一些 attar vale。我已经使用了 each 和 setTimeout 函数。最初,这行得通。但是如果我使用这段代码,一段时间后滑块会停止。请注意,此代码独立于滑块代码。

function checkForChanges() {
  $('#ninja-slider ul li').each(function(i) {
    if ($(this).hasClass("ns-show")) {
      //$(this).css("color", "red");
      console.log('yes')
    } else {
      setTimeout(checkForChanges, 3000);
      console.log('no')
    }
  });
}

$(checkForChanges);

标签: javascriptjquerysettimeouteach

解决方案


如果您想每 3 秒获得一次活动滑块,则不需要每个滑块,它可能像:

function checkForChanges() {
  //Here is the active li in the slide  
  var active_li = $("#ninja-slider li.ns-show");

  //Get the src of shwon image
  console.log( $("#ninja-slider li.ns-show").find('img').attr('src') );

  setTimeout(checkForChanges, 3000);
}

checkForChanges();

推荐阅读