How to simulate a click with JavaScript?

前端 未结 8 2259
说谎
说谎 2020-11-22 01:49

I\'m just wondering how I can use JavaScript to simulate a click on an element.

Currently I have:



        
8条回答
  •  孤独总比滥情好
    2020-11-22 02:12

    This isn't very well documented, but we can trigger any kinds of events very simply.

    This example will trigger 50 double click on the button:

    let theclick = new Event("dblclick")
    
    for (let i = 0;i < 50;i++){
      action.dispatchEvent(theclick) 
    }
    
    

    The Event interface represents an event which takes place in the DOM.

    An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent().

    https://developer.mozilla.org/en-US/docs/Web/API/Event

    https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

提交回复
热议问题