如何触发JavaScript事件单击

时间:2021-06-30 08:40:44

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事件触发器。

8 个解决方案

#1


177  

Add an ID to your link

在链接中添加一个ID。

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

and call it in your javascript code:

在javascript代码中调用:

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

#2


75  

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=“某物”不会触发更改事件。

#3


32  

What

什么

 l.onclick();

does is exactly calling the onclick function 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,

如果你已经设置了l,它就是调用l的onclick函数。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);

#4


19  

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)。将以下代码输入控制台(一般为一行):

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

This will generate the required result

这将生成所需的结果

#5


8  

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.dispatchEvent or el.fireEvent where el will be your Anchor element. I believe both of these will require constructing an Event object to pass in.

要手动触发事件,您需要为不同的浏览器使用不同的方法—el。dispatchEvent或el。将el作为锚元素的fireEvent。我相信这两个都需要构造一个事件对象来传入。

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.

#6


7  

.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 docs)。您可以使用此方法触发单击事件:

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

从这篇文章

#7


1  

Fair warning:

公平的警告:

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

onclick()不按预期运行。它只运行onclick=""属性中的代码,但不触发默认行为。

I had similar issue with radio button not setting to checked, even though onclick custom 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自定义功能运行良好。必须添加收音机。检查= " true ";设置它。对于其他元素(a.onclick()之后,也应该有window.location。href = " url ";)

#8


0  

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/

#1


177  

Add an ID to your link

在链接中添加一个ID。

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

and call it in your javascript code:

在javascript代码中调用:

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

#2


75  

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=“某物”不会触发更改事件。

#3


32  

What

什么

 l.onclick();

does is exactly calling the onclick function 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,

如果你已经设置了l,它就是调用l的onclick函数。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);

#4


19  

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)。将以下代码输入控制台(一般为一行):

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

This will generate the required result

这将生成所需的结果

#5


8  

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.dispatchEvent or el.fireEvent where el will be your Anchor element. I believe both of these will require constructing an Event object to pass in.

要手动触发事件,您需要为不同的浏览器使用不同的方法—el。dispatchEvent或el。将el作为锚元素的fireEvent。我相信这两个都需要构造一个事件对象来传入。

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.

#6


7  

.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 docs)。您可以使用此方法触发单击事件:

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

从这篇文章

#7


1  

Fair warning:

公平的警告:

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

onclick()不按预期运行。它只运行onclick=""属性中的代码,但不触发默认行为。

I had similar issue with radio button not setting to checked, even though onclick custom 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自定义功能运行良好。必须添加收音机。检查= " true ";设置它。对于其他元素(a.onclick()之后,也应该有window.location。href = " url ";)

#8


0  

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/