【问题标题】:Click event in for loop | i value is always the last valuefor 循环中的单击事件 | i 值始终是最后一个值
【发布时间】:2016-07-10 15:00:56
【问题描述】:

我是 CasperJS 初学者。

我想遍历 ul 的所有 li 并单击每个 li。单击 li 时,会弹出一个模态并保存模态数据。但是循环内'i'的值始终是最终值。
我在 ul 中有 5 个 lis。
以下循环总是在第 5 li 上单击 5 次,并在单击第 5 li 时保存模态数据 5 次。

casper.then(function() {
  a = lis.length;
  this.echo(a + ' lis found');
  for(var i = 1; i <= a; i++ ) {
    this.echo(i + ' now');
    this.click('.hello:nth-child('+ i +')' );
    casper.waitUntilVisible('.modal__content ', function() {
      console.log('Open Modal');
      links = links.concat(this.evaluate(getLinks));
    });
  }
});

我搜索了一下,发现我们应该将事件侦听器的分配包装在一个闭包中。但这并没有回应任何东西。

casper.then(function() {
  a = lis.length;
  this.echo(a + ' lis found');
  for(var i = 1; i <= a; i++ ) {
    (function(i){  // Added this line
      this.echo(i + ' now');
      this.click('.hello:nth-child('+ i +')' );
      casper.waitUntilVisible('.modal__content ', function() {
        console.log('Open Modal');
        links = links.concat(this.evaluate(getLinks));
      });
    })(i); // Added this line
  }
});

【问题讨论】:

    标签: javascript phantomjs casperjs


    【解决方案1】:

    将 click 更改为 thenClick 解决了问题:)

    casper.then(function() {
      a = lis.length;
      this.echo(a + ' lis found');
      for(var i = 1; i <= a; i++ ) {
        this.echo(i + ' now');
        this.thenClick('.hello:nth-child('+ i +')' ); // Changed to thenClick from click
        casper.waitUntilVisible('.modal__content ', function() {
          console.log('Open Modal');
          links = links.concat(this.evaluate(getLinks));
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2016-05-08
      • 2023-03-31
      • 2012-04-06
      • 2022-01-25
      相关资源
      最近更新 更多