[英]How does one programmatically click a button via the browser console [code inside]
For some reason, I am able to click some links/buttons, but cannot for buttons/anything that has an onclick attribute. 出于某种原因,我可以单击某些链接/按钮,但不能用于具有onclick属性的按钮/任何内容。 For example: my JavaScript code I input into the browser's console:
例如:我输入浏览器控制台的JavaScript代码:
var o = document.getElementsByName("takepic");
for (var i = 0; i < 1000; i++){
o.click();
console.log(i);
}
I put console.log so I know what the browser is doing, and where it currently is at. 我把console.log放进去,所以我知道浏览器正在做什么,以及它目前在哪里。
The html code on the page: 页面上的html代码:
<form>
<input type="button" value="Configure..." onclick="webcam.configure()">
<input type="button" value="Take Snapshot" onclick="take_snapshot()" name="takepic">
</form>
So basically, I want to take rapid snapshots using the browser console, but when I enter in my code, I get this error: 基本上,我想使用浏览器控制台拍摄快速快照,但是当我输入我的代码时,我收到此错误:
TypeError: Object # has no method 'click'
TypeError:Object#没有方法'click'
When I do use the same code, say for re-adding friends on facebook, and I use this: 当我使用相同的代码时,比如在Facebook上重新添加朋友,我使用这个:
var o = document.getElementsByName("fbaddfriend_example");
for (var i = 0; i < o.length; i++){
o[i].click();
console.log(i);
}
It definitely works. 绝对有效。 I'm just trying to do the same with a button on a page, but with no avail.
我只是试图用页面上的按钮做同样的事,但没有用。
Your problem is in the code you're typing into the console. 您的问题出在您在控制台中输入的代码中。 You are using
document.getElementsByName()
, which will return an array of elements. 您正在使用
document.getElementsByName()
,它将返回一个元素数组。 You need to loop through those elements. 你需要遍历这些元素。 You are doing this in your second code segment, but not your first.
您是在第二个代码段中执行此操作,但不是第一个。
var o = document.getElementsByName("takepic");
for (var j = 0; j < o.length; j++) {
for (var i = 0; i < 1000; i++){
o[j].click();
console.log(i);
}
}
Change the code to: 将代码更改为:
var o = document.getElementsByName("takepic");
for (var i = 0; i < 1000; i++){
// ---v
o[i].click();
console.log(i);
}
The variable o
holds a collection of all retrieved elements. 变量
o
包含所有检索元素的集合。 o[i]
returns the element at position i
. o[i]
返回位置i
的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.