[英]Clicking a button in JavaScript
As far as I can tell from my very limited knowledge about JavaScript, it can get all kinds of info about some elements on the page, for example, about a button. 据我对JavaScript的了解非常有限,它可以获取有关页面上某些元素(例如,按钮)的各种信息。 JavaScript can get the name of a button, its type, name, and the text in it.
JavaScript可以获取按钮的名称,按钮的类型,名称以及其中的文本。 It can even disable a button.
它甚至可以禁用按钮。 But can it simulate a click on a button?
但是它可以模拟点击按钮吗? Or it can and must only be done by a user?
还是只能由用户完成?
EDIT 1 (my response to the answer below written by Narxx ): 编辑1 (我对以下由Narxx回答的回答):
This way doesn't seem to work: 这种方式似乎不起作用:
<html>
<head>
<script type="text/javascript">
document.getElementById('my-button').click();
</script>
</head>
<body>
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
EDIT 2 (my response to the comment below written by prash ) 编辑2 (我对以下由prash撰写的评论的回复 )
This way doesn't work either (the simulate function is written by kangas , modified by TweeZz , and is taken by me from here ): 这种方式不工作或者(在模拟功能是通过书面卡加斯 ,通过TweeZz修改,并从我拍这里 ):
<html>
<head>
<script type="text/javascript">
function simulate(element, eventName)
{
var options = extend(defaultOptions, arguments[2] || {});
var oEvent, eventType = null;
for (var name in eventMatchers)
{
if (eventMatchers[name].test(eventName)) { eventType = name; break; }
}
if (!eventType)
throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
if (document.createEvent)
{
oEvent = document.createEvent(eventType);
if (eventType == 'HTMLEvents')
{
oEvent.initEvent(eventName, options.bubbles, options.cancelable);
}
else
{
oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
}
element.dispatchEvent(oEvent);
}
else
{
options.clientX = options.pointerX;
options.clientY = options.pointerY;
var evt = document.createEventObject();
oEvent = extend(evt, options);
element.fireEvent('on' + eventName, oEvent);
}
return element;
}
function extend(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
var eventMatchers = {
'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
pointerX: 0,
pointerY: 0,
button: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
bubbles: true,
cancelable: true
}
simulate(document.getElementById("btn"), "click");
</script>
</head>
<body>
<button id="btn" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
EDIT 3: (my response to the answer below written by Jonco98 ): 编辑3 :(我对以下由Jonco98回答的回答):
( This code is also the answer to my question ) ( 此代码也是我的问题的答案 )
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ClickButton()
{
document.getElementById('my-button').click();
}
</script>
</head>
<body onload="ClickButton()">
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
EDIT 4: 编辑4:
Please note that the answer below given by naomik also solves my problem perfectly well. 请注意, naomik给出的以下答案也很好地解决了我的问题。
I would recommend doing this unobtrusively . 我建议您这样做不要打扰 。
<button id="my-button">The Time is?</button>
<script type="text/javascript">
var b = document.getElementById("my-button");
function displayTime(elem) {
elem.innerHTML = Date();
}
b.addEventListener("click", function(event) {
displayTime(this);
});
// fake the click
b.dispatchEvent(new Event("click"));
</script>
The button loads and is "clicked" with the simulated event immediately. 该按钮将立即加载并被“模拟事件”“单击”。 Subsequent clicks will result in the button time being updated.
随后的点击将导致按钮时间被更新。
Here's another example: 这是另一个例子:
The time will stop updating after you click submit 单击提交后,时间将停止更新
<form id="my-form">
<input name="time" />
<input type="submit" />
</form>
<script type="text/javascript">
var f = document.getElementById("my-form");
function updateTime() {
f.time.value = Date();
}
var interval = setInterval(updateTime, 1000);
f.addEventListener("submit", function(event) {
clearInterval(interval);
alert("the submitted time is: " + f.time.value);
event.preventDefault();
});
// prepopulate form
updateTime();
</script>
References 参考
Yes, you can simulate a click on a button using JavaScript: 是的,您可以使用JavaScript模拟按钮的点击:
HTML: HTML:
<button id="my-button">Click me</button>
JS: JS:
document.getElementById('my-button').click();
That's it... you have just triggered a click event on a button without actually clicking it :) 就是这样...您刚刚在按钮上触发了click事件,而没有实际单击它:)
Well, this is not meant as the alternate answer. 好吧,这并不意味着是替代答案。 The answer is already there as suggested by @naomik, and I agree with that.
正如@naomik所建议的那样,答案已经在那里,我同意这一点。
Let me point out the issue what the OP faced and is unclear why his actual code didn't work though. 让我指出OP面临的问题,但不清楚为什么他的实际代码不起作用。
Actual code: 实际代码:
<html>
<head>
<script type="text/javascript">
document.getElementById('my-button').click();
</script>
</head>
<body>
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
Simple reason why this didn't trigger the event is because , The <button>
was not painted at that time, and you would have got this error in your console Cannot read property 'click' of null
导致事件不触发的简单原因是,当时未绘制
<button>
,并且您在控制台中会收到此错误。 Cannot read property 'click' of null
In the first example that @naomik has shared, this seems to work though. 在@naomik共享的第一个示例中,这似乎可行。 Reason being the place where the
<script>
is executed. 原因是执行
<script>
位置。 It is not in the <head>
, Its inside the <body>
, and the <button>
is painted first before the script execution. 它不在
<head>
,它在<body>
,并且<button>
在执行脚本之前首先被绘制。
This is good, 很好啊
<html>
<head></head>
<body>
<button id="my-button" onclick="this.innerHTML=Date()">The time is?</button>
<script type="text/javascript">
document.getElementById('my-button').click();
</script>
</body>
</html>
Apart from this, it is advisable to do this via dispatchEvent()
and addEventListener()
to simulate and listen to the event. 除此之外,建议通过
dispatchEvent()
和addEventListener()
进行此操作以模拟和侦听事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.