使用 Javascript - 如何单击没有 ID、值或名称的提交按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15925057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Javascript - How to Click a Submit Button that has No ID, Value or Name
提问by Learning
How can I use javascript to "click" a button that has no id, value, class or name?
如何使用 javascript 来“点击”一个没有 ID、值、类或名称的按钮?
The relevant code for the button is:
按钮的相关代码是:
<div class="classname anotherclassname" title="">
<div>
<button type="submit"><i class="anotherclass anotherclassname"></i>ImAButton</button>
</div>
</div>
I'd give an example of what I have so far, as I know that is simply good etiquette here on stackoverflow, but I don't even know where to start. The only way I presently know how to use javascript to click a button is using this:
我会举一个到目前为止我所拥有的例子,因为我知道这在 stackoverflow 上只是一个很好的礼仪,但我什至不知道从哪里开始。我目前知道如何使用 javascript 单击按钮的唯一方法是使用这个:
document.getElementById("myButtonId").click();
And that doesn't apply here.
这在这里不适用。
回答by Christofer Eliasson
If you are okay with only supporting modern browsers and IE8 and above, then you could use document.querySelectorAll
to select the element. Given that the button is the only button of type submit on the page, you could do:
如果您只支持现代浏览器和 IE8 及更高版本,那么您可以使用document.querySelectorAll
来选择元素。鉴于该按钮是页面上唯一的提交类型按钮,您可以执行以下操作:
document.querySelectorAll("button[type='submit']")[0].click();
querySelectorAll takes any valid CSS-selector (IE8 only support CSS2 selectors). So if you need to make the selection more specific, you could just make the selector more specific as you would with any CSS-selector. Something like this for example:
querySelectorAll 接受任何有效的 CSS 选择器(IE8 仅支持 CSS2 选择器)。因此,如果您需要使选择更加具体,您可以使选择器更加具体,就像使用任何 CSS 选择器一样。例如这样的事情:
document.querySelectorAll(".classname button[type='submit'"])[0].click();
回答by Khaleel
You can get all button on page using
您可以使用页面上的所有按钮
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[0].click();
may fire a click on the first button.
可能会触发第一个按钮的点击。