简体   繁体   English

Javascript click() 对某些元素不起作用

[英]Javascript click() doesn't work on some elements

I want to write some automation to website.我想为网站编写一些自动化。 Simply filling in forms and simulating clicks on elements.只需填写表格并模拟对元素的点击。 But for some elements JavaScript function click() doesn't work.但是对于某些元素,JavaScript 函数 click() 不起作用。 For example it is on this page: http://www1.plus.pl/bsm/ If I do click() on "Wyślij" button, nothing happens.例如,它在此页面上: http ://www1.plus.pl/bsm/ 如果我在“Wyślij”按钮上单击(),则没有任何反应。 It is my command:这是我的命令:

document.getElementsByClassName('tab-button')[0].click()

What is wrong?怎么了? Why on other elements this function works?为什么这个功能在其他元素上有效?

With yours help I found the solution:在您的帮助下,我找到了解决方案:

var evt = document.createEvent('MouseEvents')
evt.initMouseEvent('mousedown', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.querySelectorAll('.tab-button')[0].dispatchEvent(evt)

Notice that it should be mousedown event rather than click .请注意,它应该是mousedown事件而不是click Some sites are done in a different way than others.有些网站的制作方式与其他网站不同。 Another important thing is 3rd parameter.另一个重要的事情是第三个参数。 It should be set to false (in this particular case).它应该设置为false (在这种特殊情况下)。 It sets cancelable value.它设置cancelable值。 Without this set to false it doesn't work.如果不将此设置为false则它不起作用。

Thank you for all answers!谢谢大家的回答!

document.getElementsByClassName('tab-button')[0].dispatchEvent(event)

or或者

document.getElementsByClassName('tab-button')[0].fireEvent(event)

is the way you could do it... but trying it on the site, the 'click' event isn't bound to that element是你可以做到的方式......但是在网站上尝试时,“点击”事件并未绑定到该元素

EDITED See How to trigger event in JavaScript?已编辑请参阅如何在 JavaScript 中触发事件?

I would suspect that it is because the browser you are testing on has no native support for .getElementsByClassName .我怀疑这是因为您正在测试的浏览器没有对.getElementsByClassName本机支持。 Try using document.querySelectorAll instead, or assign your element an ID and use document.getElementById .尝试改用document.querySelectorAll ,或者为您的元素分配一个 ID 并使用document.getElementById Eg:例如:

var btn = document.querySelectorAll("tab-button")[0];
btn.click();

It seems like some elements need dispatchEvent() , and others need a plain click() .似乎有些元素需要dispatchEvent() ,而其他元素则需要简单的click() To build on gumik's answer (thanks!), here's my copy-pasta for quick-and-dirty Javascript automation that just needs to click things:为了建立在 gumik 的回答之上(谢谢!),这是我的复制面食,用于快速而肮脏的 Javascript 自动化,只需要点击一些东西:

function click(node) {
  var evt = document.createEvent('MouseEvents');
  evt.initMouseEvent('mousedown', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  node.dispatchEvent(evt);
  
  node.click();
}

Usage:用法:

var button = document.querySelector(".somecssclassname");
click(button);

您在Loaded body标签后是否执行此操作,如果某些元素未单击,则可能是由于脚本运行时它们未加载到 DOM 中。

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

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