很奇怪, 我在一张网页上模拟点击事件, 但是貌似, 只有追后一个click()生效.

for循环无效
var pics=[].slice.apply(document.getElementsByTagName('button'));
(async function down() {
	for(var id=0;id<pics.length;++id) {
		let pic=pics[id];
		let style=pic.className;
		let regdown=/down/im;
		let regno=/del|danger/im;
		if(regdown.test(style)&&!regno.test(style)) {
			pic.click();
			await sleep(1);
		}
	}
}) ();

递归无效
var pics=[].slice.apply(document.getElementsByTagName('button'));
let length=pics.length

let regdown=/down/im;
let regno=/del|danger/im;
var time=100;
(async function dow(i=0) {
	console.log("kaishila: ",i,"   legth:", length);
	
	if(i>=length) {
		return;
	}
	let pic=pics[i];
	let style=pic.className;
	if(regdown.test(style)&&!regno.test(style)) {
		pic.click();
		console.log(pic.textContent);
		
	}
	await sleep(time);	
	return setTimeout(e => dow(++i),time);
})()


  • 其实是有效的, 就是间隔时间的问题. 只要间隔时间ok, 那么就OK, 问题来了, 如何调整间隔时间呢?
js模拟事件

例如模拟点击事件

//方法一
The createEvent method is deprecated. Use event constructors instead.

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

element.dispatchEvent(clickEvent);

//方法二
element.click();

https://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-javascript/22469115#22469115

事件仅仅执行一次
<button onclick="myFunction(); this.onclick=null;">This button works only once</button>