javascript 如何在浏览器控制台中按名称单击按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25919045/
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
How to Click a Button by Name in Browser Console
提问by Alex
I am trying to click a button on a web page using the developer tools console in Google Chrome.
我正在尝试使用 Google Chrome 中的开发人员工具控制台单击网页上的按钮。
The HTML for the button is:
按钮的 HTML 是:
<input value="Send an Email" class="btn" name="email" onclick="navigateToUrl('/_ui/core/email/author/EmailAuthor?p2_lkid=00QU0000008xZYi&rtype=00Q&retURL=%2F00QU0000008xZYi','RELATED_LIST','email');" title="Send an Email" type="button">
As you can see, the button does not have an id
attribute, so I'm trying to select it using the name
attribute. My JavaScript code is:
如您所见,该按钮没有id
属性,因此我尝试使用该name
属性来选择它。我的 JavaScript 代码是:
document.getElementsByName("email").click()
What am I doing wrong?
我究竟做错了什么?
回答by j08691
document.getElementsByName
returns an array (technically a NodeList), so you have to specify the element you want like:
document.getElementsByName
返回一个数组(技术上是一个NodeList),所以你必须指定你想要的元素:
document.getElementsByName("email")[0].click()
回答by epascarello
Elements = plural = node List
元素 = 复数 = 节点列表
You need to select the first one.
您需要选择第一个。
document.getElementsByName("email")[0].click()
回答by LcSalazar
It's been well answered that the issue relies on the fact that document.getElementsByName()
returns a node list, not a single element.
已经很好地回答了该问题依赖于document.getElementsByName()
返回节点列表而不是单个元素的事实。
Just to point an alternative, no list returnmethod:
只是指出一个替代方法,没有列表返回方法:
If you want to browse for a single element, and do not have an id, but needs to look for any attribute (not just name), you could call it using document.querySelector()
, that uses a css-like selector, and returns the first matched element, so:
如果您想浏览单个元素,并且没有 id,但需要查找任何属性(不仅仅是名称),您可以调用它 using document.querySelector()
,它使用类似 css 的选择器,并返回第一个匹配的元素, 所以:
var element = document.querySelector("[name='email']");