javascript - 函数到达末尾后如何再次运行它?

标签 javascript

到达数组中的最后一个值后如何再次运行循环?

我想在函数 init() 完成后再次运行它,因为更多的 DOM 元素 myElement 一旦被点击就会被 ajax 进来。

我尝试在 setTimeout 之后运行 init 函数,但这不起作用,并尝试使用 btn.length -1< 检查数组上的最后一个元素 仍然不起作用。

function doSetTimeout(index, btn) {

    setTimeout(function() { 
        jQuery(btn[index]).click(); 
    }, index  * 1500);

    //init();   

}

function init() {

    var btn = [].slice.call(document.querySelectorAll('.myElement'));

    var index;

    for (index = 0; index < btn.length; index++) {

        doSetTimeout(index, btn)

    }

}

init();

最佳答案

这有效吗?

function init() {

    var btn = [].slice.call(document.querySelectorAll('.myElement'));

    var index = 0;

    function click() {
      setTimeout(function() {
          if(index < btn.length) {
            jQuery(btn[index++]).click();
            click();
          } else {
            init();
          }
      }, 1500);
    }
    click();
}

关于javascript - 函数到达末尾后如何再次运行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562324/

相关文章:

javascript - 如何从 Polygon 动态更新 SVG viewBox 值

javascript - jquery.each - 将计数器传递给子 .onload 函数

php - 在 php 中检索 Get Http 请求

javascript - CSS 在 DevExtreme 中切换子菜单

javascript - 检查字符串是否包含日文/中文字符

javascript - JS promise : Allowing Propagation of Errors

javascript - 仅保护命名 View 路由器下的一个组件 - Vue js

javascript - 从 golang 服务器在浏览器中下载压缩文件

javascript - InDesign CS4 - Javascript - 使文本区域透明

javascript - 与 requirejs 连接并排除单个文件?