简体   繁体   English

Javascript单击多个按钮之一

[英]Javascript clicking one of multiple buttons

There are two buttons present in a form, and I would like to use GreaseMonkey to automatically click one of the buttons when the page loads.表单中有两个按钮,我想使用 GreaseMonkey 在页面加载时自动单击其中一个按钮。 The two buttons are:这两个按钮是:

<td rowspan="2"><input class="first action" name="first" type="submit" value="First Action" style="font-size: 10pt;" /></td>
<td rowspan="2"><input class="second action" name="second" type="submit" value="Second Action" style="font-size: 10pt;" /></td>

I have tried the two below codes, but neither are working.我试过下面的两个代码,但都没有工作。 The first selects the form and tries to submit it, and I get an error that says "No Action Permitted."第一个选择表单并尝试提交它,我收到一条错误消息,显示“不允许操作”。 The second tries to click() the button.第二个尝试 click() 按钮。

First:第一的:

var button = document.getElementById('units_form');
window.location(button);

Second:第二:

var button = document.getElementByClassName('first action');
button.click();

First off, the generic solution:首先,通用解决方案:

  • to get an element object by class name, use document.getElementsByName("class_name")[0] . document.getElementsByName("class_name")[0]类名获取元素对象,请使用document.getElementsByName("class_name")[0] The last part [0] gives you the first of all elements that have this class最后一部分[0]为您提供了具有此类的所有元素中的第一个
  • To fire an event on element, see this article on MDN .要在元素上触发事件,请参阅MDN 上的这篇文章 I strongly advise to read it all .我强烈建议阅读所有内容 Judging from your post you're quite lazy when it comes to reading articles.从您的帖子来看,您在阅读文章时非常懒惰。

Putting it all together:把它们放在一起:

var button_element = document.getElementsByName("button-class-name")[0];
var event_object = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
});
button_element.dispatchEvent(event_object);

Also, most sites use jQuery library, for which it boils down to:此外,大多数网站使用 jQuery 库,归结为:

$(".class_name").click();

Note that this will fire on all elements with that class name.请注意,这将在具有该类名的所有元素上触发。

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

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