如何触发 JavaScript 事件单击

2022-08-30 00:18:29

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

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

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


答案 1

对 HTML 元素执行一次单击:只需执行.大多数主流浏览器都支持此功能element.click()


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

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

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

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

答案 2

更新

这是一个老答案。如今,您应该只使用点击。对于更高级的事件触发,请使用 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'));

原始答案

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

更新以与 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);
    }
};

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