javascript 使用javascript以编程方式单击非按钮元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20870975/
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
Programmatically click on a non-button element using javascript?
提问by Kevin
How to programmatically click on a non-button element using javascript? Or is it atleast possible in browsers like Firefox and Chrome?
如何使用javascript以编程方式单击非按钮元素?或者至少可以在 Firefox 和 Chrome 等浏览器中使用?
采纳答案by T.J. Crowder
Believe it or not, for a fairly basic click, you can just call click
on it (but more below): Live Example| Live Source
信不信由你,对于一个相当基本的点击,你可以调用click
它(但更多如下):Live Example| 直播源
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Artificial Click</title>
</head>
<body>
<div id="foo">xxxxxxx</div>
<script>
(function() {
var foo = document.getElementById("foo");
foo.addEventListener("click", function() {
display("Clicked");
}, false);
setTimeout(function() {
display("Artificial click:");
foo.click(); // <==================== The artificial click
}, 500);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
You can also create the relevant type of Event
object and use dispatchEvent
to send it to the element:
您还可以创建相关类型的Event
对象并用于dispatchEvent
将其发送到元素:
var e = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true
});
foo.dispatchEvent(e);
This gives you the opportunity to do things like set other information (the typical pageX
and pageY
, for instance) on the event you're simulating.
这使您有机会在您模拟的事件上设置其他信息(例如,典型pageX
和pageY
)。
More about the various event object types in Section 5of the DOM Events spec.
更多关于DOM 事件规范的第 5 节中的各种事件对象类型。
回答by laaposto
回答by Hyman
Or in jQuery (documentation) to click on a non-button element
或者在 jQuery(文档)中点击一个非按钮元素
$( "#nonButton" ).click();
or to listen for a click on that non-button element
或监听对该非按钮元素的点击
$("#nonButton").on("click", doSomething);
回答by Liu Chong
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.getElementById("nonButton").dispatchEvent(evt);
see: https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent
请参阅:https: //developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent
回答by Naloiko Eugene
document.querySelectorAll('#front-chat-container div[role]')[0].click()
worked for me - to click a div element.
对我来说有效 - 单击一个 div 元素。