简体   繁体   English

您如何使用javascript查找并单击网页上的特定按钮?

[英]How do you find and click on a specific button on a webpage using javascript?

Basically, I'm trying to write a command-line client-side script (javascript) for purchasing something online automatically. 基本上,我试图编写一个命令行客户端脚本(javascript)以自动在线购买商品。

The problem is that on this particular webpage the button I'm trying to click (add to cart) appears several times in the page (for different products). 问题是,在这个特定的网页上,我尝试单击的按钮(添加到购物车)在页面中出现了几次(针对不同的产品)。

I know that: 我知道:

document.getElementById('addToCart').submit();

will click on addToCart , but since there are several buttons with that same name how can I find and click on the specific button for a certain product? 将单击addToCart ,但是由于有多个同名按钮,我如何找到并单击特定产品的特定按钮?

We can assume that we know the product name in advance and that each addToCart button has a unique id (which I don't know). 我们可以假设我们事先知道产品名称,并且每个addToCart按钮都有一个唯一的ID(我不知道)。

您可以自己回答,如果您已经知道产品名称,那么您肯定已经知道它是按钮的ID吗?

document.getElementById('button234').click()

There should never be more than one element on a page by a specific ID. 特定ID在页面上的元素不得超过一个。 If you need more than one element, use the class attribute. 如果需要多个元素,请使用class属性。

As SmokeyPHP writes, you can use .click() or .submit() to trigger the click event. 作为SmokeyPHP写道,您可以使用.click().submit()来触发点击事件。

everyone is correct you should only have a single ID but here a little more narative of how you can do this. 每个人都是正确的,您应该只具有一个ID,但在这里更多地叙述如何执行此操作。

So you are saying you have some dynamically generated HTML right? 因此,您是说您拥有一些动态生成的HTML吗? You get a list of products back and you could have a list of buttons that looks like the following. 您会获得一个产品列表,并且可能有一个如下所示的按钮列表。

<input id="productId_233442" class="addToCart" type="button" value="addToCart"></input><br/>
<input id="productId_25AD22" class="addToCart" type="button" value="addToCart"></input><br/>
<input id="productId_1J3422" class="addToCart" type="button" value="addToCart"></input><br/>

For styling purposes you could give them all the same class of addToCart as in the above example. 出于样式目的,您可以为他们提供与上述示例相同的addToCart类。

As for the java script you could have something like this. 至于Java脚本,您可能会有类似的内容。

$(document).ready(function(){
  $(document).click(function(event){
        alert(event.target.id);
    });
});

I am using JQuery which I would suggest but you can do this in pure JS if you wanted but I can't imagine why you would. 我正在使用我建议的JQuery,但是如果您愿意,您可以在纯JS中执行此操作,但我无法想象为什么会这样做。

see the following fiddle. 参见下面的小提琴。 http://jsfiddle.net/r0k3t/dRam5/ http://jsfiddle.net/r0k3t/dRam5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM