我的网页上有一个超链接。出于测试的目的,我正在尝试自动单击超链接。是否有任何方法可以使用JavaScript模拟超链接上的50次单击?

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

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


当前回答

你应该只使用点击。对于更高级的事件触发,请使用dispatchEvent。

Const body = document.body; 的身体。addEventListener('点击',e => { console.log(“点击”身体); }); console.log(使用单击()); body.click (); console.log(“使用dispatchEvent”); 的身体。dispatchEvent(新事件(单击));

原来的答案-过时

下面是我在IE9+ http://jsfiddle.net/mendesjuan/rHMCy/4/中使用的

/**
 * 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);
    }
};

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

其他回答

你应该只使用点击。对于更高级的事件触发,请使用dispatchEvent。

Const body = document.body; 的身体。addEventListener('点击',e => { console.log(“点击”身体); }); console.log(使用单击()); body.click (); console.log(“使用dispatchEvent”); 的身体。dispatchEvent(新事件(单击));

原来的答案-过时

下面是我在IE9+ http://jsfiddle.net/mendesjuan/rHMCy/4/中使用的

/**
 * 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);
    }
};

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

IE9 +

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

使用的例子:

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

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

使用测试框架

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

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

手动触发事件

为了以正确的方式手动触发事件,您需要为不同的浏览器使用不同的方法-或者el。dispatchEvent或el。其中el将是你的Anchor元素。我认为这两种方法都需要构造一个Event对象来传递。

另一种不完全正确的快捷方式是这样的:

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

公平的警告:

Element.onclick()的行为不像预期的那样。它只运行onclick=""属性内的代码,但不会触发默认行为。

我有类似的问题,单选按钮没有设置为选中,即使onclick自定义功能运行良好。不得不增加无线电。Checked = "true";来设置。可能同样适用于其他元素(在a.onclick()之后也应该有window.location.href = "url";)


请在按钮点击的任何地方调用触发功能。


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

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