How can I trigger a JavaScript event click

后端 未结 9 2034
迷失自我
迷失自我 2020-11-22 02:56

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

相关标签:
9条回答
  • 2020-11-22 03:48

    Please call trigger function any where and button will click.


    <a href="#" id="myBtn" title="" >Button click </a>
    
    function trigger(){
        document.getElementById("myBtn").click();
    }
    
    0 讨论(0)
  • 2020-11-22 03:50

    UPDATE

    This was an old answer. Nowadays you should just use click. For more advanced event firing, use 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/

    Updated to work with 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.

    0 讨论(0)
  • 2020-11-22 03:51

    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.click();
    

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

    0 讨论(0)
提交回复
热议问题