如何触发 JavaScript 事件点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2381572/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:01:27  来源:igfitidea点击:

How can I trigger a JavaScript event click

javascriptdom-events

提问by user171523

I have a hyperlink in my page. I am trying to automate a number of clicks on the hyperlink for testing purposes. Is there any way you can simulate 50 clicks on the hyperlink using JavaScript?

我的页面中有一个超链接。我正在尝试自动点击超链接以进行测试。有什么方法可以使用 JavaScript 模拟超链接上的 50 次点击?

<a href="#" target="_blank" onclick="javascript:Test("Test");">MSDN</a>

I'm looking for onClick event trigger from the JavaScript.

我正在从 JavaScript 中寻找 onClick 事件触发器。

回答by instanceof me

Performing a single click on an HTML element:Simply do element.click(). Most major browsers support this.

在 HTML 元素上执行一次单击:只需执行element.click(). 大多数主要浏览器都支持这一点



To repeat the click more than once:Add an ID to the element to uniquely select it:

要多次重复单击:向元素添加 ID 以唯一选择它:

<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>

and call the .click()method in your JavaScript code via a for loop:

.click()通过 for 循环调用JavaScript 代码中的方法:

var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
   link.click();

回答by Juan Mendes

UPDATE

更新

This was an old answer. Nowadays you should just use click. For more advanced event firing, use dispatchEvent.

这是一个旧的答案。现在你应该只使用click。对于更高级的事件触发,请使用dispatchEvent

const body = document.body;

body.addEventListener('click', e => {
  console.log('clicked body');
});

console.log('Using click()');
body.click();

console.log('Using dispatchEvent');
body.dispatchEvent(new Event('click'));

Original Answer

原答案

Here is what I use: http://jsfiddle.net/mendesjuan/rHMCy/4/

这是我使用的:http: //jsfiddle.net/mendesjuan/rHMCy/4/

Updated to work with IE9+

更新以使用 IE9+

/**
 * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
 * by testing for a 'synthetic=true' property on the event object
 * @param {HTMLNode} node The node to fire the event handler on.
 * @param {String} eventName The name of the event without the "on" (e.g., "focus")
 */
function fireEvent(node, eventName) {
    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9){
        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }

     if (node.dispatchEvent) {
        // Gecko-style approach (now the standard) takes more work
        var eventClass = "";

        // Different events have different event classes.
        // If this switch statement can't map an eventName to an eventClass,
        // the event firing is going to fail.
        switch (eventName) {
            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;

            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;

            default:
                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);
        event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

        event.synthetic = true; // allow detection of synthetic events
        // The second parameter says go ahead with the default action
        node.dispatchEvent(event, true);
    } else  if (node.fireEvent) {
        // IE-old school style, you can drop this if you don't need to support IE8 and lower
        var event = doc.createEventObject();
        event.synthetic = true; // allow detection of synthetic events
        node.fireEvent("on" + eventName, event);
    }
};

Note that calling fireEvent(inputField, 'change');does not mean it will actually change the input field. The typical use case for firing a change event is when you set a field programmatically and you want event handlers to be called since calling input.value="Something"won't trigger a change event.

请注意,调用fireEvent(inputField, 'change');并不意味着它实际上会更改输入字段。触发更改事件的典型用例是当您以编程方式设置字段并且您希望调用事件处理程序时,因为调用input.value="Something"不会触发更改事件。

回答by u2546233

What

什么

 l.onclick();

does is exactly calling the onclickfunction of l, that is, if you have set one with l.onclick = myFunction;. If you haven't set l.onclick, it does nothing. In contrast,

do 正是调用了 的onclick函数l,也就是说,如果你已经用l.onclick = myFunction;. 如果你没有设置l.onclick,它什么都不做。相比之下,

 l.click();

simulates a click and fires all event handlers, whether added with l.addEventHandler('click', myFunction);, in HTML, or in any other way.

模拟单击并触发所有事件处理程序,无论是使用l.addEventHandler('click', myFunction);、在 HTML 中添加还是以任何其他方式添加。

回答by htmldrum

I'm quite ashamed that there are so many incorrect or undisclosed partial applicability.

我很惭愧有这么多不正确或未公开的部分适用性。

The easiest way to do this is through Chrome or Opera (my examples will use Chrome) using the Console. Enter the following code into the console (generally in 1 line):

最简单的方法是使用控制台通过 Chrome 或 Opera(我的示例将使用 Chrome)。在控制台中输入以下代码(一般在 1 行):

var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
  l.click();
}

This will generate the required result

这将生成所需的结果

回答by Manolo

.click()does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:

.click()不适用于 Android(在移动部分查看mozilla 文档)。您可以使用此方法触发点击事件:

function fireClick(node){
    if (document.createEvent) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);    
    } else if (document.createEventObject) {
        node.fireEvent('onclick') ; 
    } else if (typeof node.onclick == 'function') {
        node.onclick(); 
    }
}

From this post

这个帖子

回答by Nicole

Use a testing framework

使用测试框架

This might be helpful - http://seleniumhq.org/- Selenium is a web application automated testing system.

这可能会有所帮助 - http://seleniumhq.org/- Selenium 是一个 Web 应用程序自动化测试系统。

You can create tests using the Firefox plugin Selenium IDE

您可以使用 Firefox 插件Selenium IDE创建测试

Manual firing of events

手动触发事件

To manually fire events the correct way you will need to use different methods for different browsers - either el.dispatchEventor el.fireEventwhere elwill be your Anchor element. I believe both of these will require constructing an Event object to pass in.

要手动火灾事件,你将需要使用不同的浏览器不同的方法正确的方式-无论是el.dispatchEventel.fireEvent哪里el会是你的锚元素。我相信这两个都需要构造一个 Event 对象来传入。

The alternative, not entirely correct, quick-and-dirty way would be this:

替代的,不完全正确的,快速而肮脏的方法是这样的:

var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
              // without an Event object parameter.

回答by Fatih Hayrio?lu

IE9+

IE9+

function triggerEvent(el, type){
    var e = document.createEvent('HTMLEvents');
    e.initEvent(type, false, true);
    el.dispatchEvent(e);
}

Usage example:

用法示例:

var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');

Source: https://plainjs.com/javascript/events/trigger-an-event-11/

来源:https: //plainjs.com/javascript/events/trigger-an-event-11/

回答by Arvigeus

Fair warning:

公平警告:

element.onclick()does not behave as expected. It only runs the code within onclick="" attribute, but does not trigger default behavior.

element.onclick()行为不符合预期。它只运行 内的代码onclick="" attribute,但不会触发默认行为。

I had similar issue with radio button not setting to checked, even though onclickcustom function was running fine. Had to add radio.checked = "true";to set it. Probably the same goes and for other elements (after a.onclick()there should be also window.location.href = "url";)

即使onclick自定义功能运行良好,我也有类似的单选按钮未设置为选中的问题。必须添加radio.checked = "true";才能设置它。对于其他元素可能也是如此(之后a.onclick()也应该有window.location.href = "url";

回答by Vinod Kumar



Please call trigger function any where and button will click.

请在任何地方和按钮将点击的地方调用触发函数。



<a href="#" id="myBtn" title="" >Button click </a>

function trigger(){
    document.getElementById("myBtn").click();
}