单击与选择器匹配的所有链接 [英] Click on all links matching a selector

查看:48
本文介绍了单击与选择器匹配的所有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接列表,我必须模拟这些链接才能使用CasperJS进行点击。它们都共享相同的类。

I have a list of links that I have to simulate a click on using CasperJS. They all share the same class.

但是使用 this.click('。click-me')只单击在第一个链接上。

However using this.click('.click-me') only clicks on the first link.

单击所有链接的正确方法是什么?我在想,也许我应该尝试通过 evaluate()获取链接数,然后对使用循环。但是,如果我在链接数量上使用 evaluate(),我必须使用消息进行通讯,这似乎很复杂。

What's the proper way of clicking on all the links? I'm thinking that maybe I should try to get the number of links via evaluate() and then use a for loop. But if I use evaluate() with the number of links I have to use messages to communicate back and that seems complicated.

还有更好的方法吗?

推荐答案

我最终使用nth-child()选择器来完成此操作。

I ended up using the nth-child() selector to accomplish this. Here's how...

页面:

<ul id="links">
  <li><a href="#1">1</a></li>  
  <li><a href="#2">2</a></li>  
  <li><a href="#3">3</a></li>  
</ul>

脚本:

casper.then(function() {
  var i = 1;
  this.repeat(3, function() {
    this.click('#links li:nth-child(' + i + ') a');
    i++;
  });
});

您显然不必使用重复,但是任何迭代技术都可以。

You obviously don't have to use repeat but any iteration technique should work.

这篇关于单击与选择器匹配的所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆