j查询间隔在到达最后一个元素后重新启动

jQuery interval restart after reaching last element

本文关键字:最后一个 元素 重新启动 查询      更新时间:2023-09-26

我有一个包含一些p元素的div,我使用jQuery循环它们以每5秒触发对下一个元素的单击。现在我的问题如何在单击最后一个元素后重新启动循环?

这是我的jQuery代码:

jQuery('.clickMe').each(function (ind, elem) {    
   window.setTimeout(function () {
       jQuery(elem).trigger("click");
   }, 5000 * ind);          
});

这是我的html,以防你想看到它:)

<div class='slider-circles'>
   <p class='transparent-cricles clickMe'></p>
   <p class='transparent-cricles clickMe'></p>
   <p class='transparent-cricles clickMe'></p>
   <p class='transparent-cricles clickMe'></p>
   <p class='transparent-cricles clickMe'></p>
   <p class='transparent-cricles clickMe'></p>
</div>
var ps=jQuery('.clickMe')
if (ps.length) {
    var index=0;
    setInterval(function() {
        ps.eq(index).trigger("click");
        index=(index+1)%ps.length;
    },5000);
}
$(function(){
window.setInterval(function(){
  logic();
}, 600);
});
function logic(){
   window.setTimeout(function () {
       $('.clickMe').each(function (ind, elem) {    
        window.setTimeout(function () {
           $(elem).hide();
           if(ind % 5 == 0) $('.clickMe').show();
           console.log(ind);
       }, 100 * ind);          
        });  
   },600 );
}

小提琴:https://jsfiddle.net/3how0tm0/1/

您需要在每次循环后重置它们。为了可视化我隐藏并显示您的<p>标签。您需要添加和删除触发器事件。

最后一次单击后,再次运行所有单击:

function run_clicking(elements) {
  var last_index = elements.length - 1;
  elements.each(function () (index, elem) {
                  window.setTimeout(function () {
                       jQuery(elem).trigger("click");
                       if( index == last_index ) {
                           // when last element, run it again (after 5s)
                           window.setTimeout(function () {
                                  run_clicking(elements);
                           }, 5000);
                       }
                   }, 5000 * index);
   }
}
run_clicking(jQuery('.clickMe'));

使用自定义函数在到达最后一个元素时重新启动循环:

function performInfiniteClick(){
  var len = performInfiniteClick.counter;
  $('.clickMe').each(function (i, el) {
     window.setTimeout(function () {
       $(el).trigger("click");
       len--;
       if (!len) {
          performInfiniteClick();
       }
     }, 1000 * i);          
  });
  return true;
}
performInfiniteClick.counter = $('.clickMe').length;
performInfiniteClick();

https://jsfiddle.net/7g3eo93m/

添加和删除类以了解您已单击。

var initiliazeClicks = function() {
  jQuery('.clickMe').each(function(ind, elem) {
    window.setTimeout(function() {

    jQuery(elem).addClass('clicked').removeClass('clickMe').trigger('click');
          if (jQuery('.clickMe').length == 0) {
            jQuery('.clicked').removeClass('clicked').addClass('clickMe');
            initiliazeClicks();
          }
        }, 5000 * ind);
      });
    };

    initiliazeClicks();

示例:https://jsfiddle.net/zsek6c2a/