简体   繁体   English

javascript,单击按钮

[英]javascript, button, click

I have 2 questions, both regarding clicking via js. 我有2个问题,都是关于通过js点击的问题。

So I am on a site and I wish to automate a physical click on 2 buttons, I learned that if we getElementbyId.click() we can do this. 因此,我在一个站点上,希望自动对2个按钮进行物理单击,我了解到,如果我们使用getElementbyId.click()我们可以做到这一点。 But both these buttons do not have an ID. 但是这两个按钮都没有ID。 I tried coordinate clicking and it doesn't work and also by the class but to no avail. 我尝试了坐标单击,但按班级分类均无济于事,但无济于事。

<td data-pick="red" class="red" rowspan="2"></td>

How do I click on this? 我该如何点击?

and also 并且

<button type="submit" class="btn btn-default btn-success">GO</button>

and this. 和这个。

document.getElementsByClassName doesn't work :( document.getElementsByClassName不起作用:(

It is possible to trigger a click using document.getElementsByClassName but you have to understand what you get back from document.getElementsByClassName is not an individual element, but a list which you can iterate over. 可以使用document.getElementsByClassName触发单击,但是您必须了解从document.getElementsByClassName返回的document.getElementsByClassName不是单个元素,而是可以迭代的列表。

You can trigger a click for every item in a collection by doing the following: 您可以通过执行以下操作来触发集合中每个项目的点击:

var redClassElements = document.getElementsByClassName('red');

for(var i=0;i<redClassElements.length;i++) {
    redClassElements[i].click();
}

This will do nothing if you haven't assigned a click handler to the element click() is being called on though. 如果您尚未为要调用的元素click()分配click handler ,则此操作将无效。

Also, do you really want to trigger a click on multiple elements? 另外,您是否真的要触发多个元素的点击? Your best bet is to assign the element an id as has been suggested to you. 最好的选择是为元素分配一个ID(已建议您)。 You can then use document.getElementById('theId').click() . 然后,您可以使用document.getElementById('theId').click()

Give this a try 试试这个

document.getElementsByClassName('red')[0].click();

Why [0] ? 为什么是[0]? because getElementsByClassName returns classes (matching DOM elements) in form of an array, so [0] is the index here :-) And for your second button you can trigger the click using 因为getElementsByClassName以数组形式返回类(匹配DOM元素),所以[0]是这里的索引:-)对于第二个按钮,您可以使用触发点击

document.querySelector("button[type=submit]").click();

By the way if you are using jquery then why don't you use 顺便说一句,如果您使用的是jQuery,那为什么不使用

$(".red").click();
$("button[type=submit]").click();

Anyways both solutions should work. 无论如何,两种解决方案都应该起作用。 Hope that helps :-) 希望有帮助:-)

使用jQuery ..

$('td[class="red"], button[class="btn btn-default btn-success"]').click();

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

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