How to simulate a click with JavaScript?

前端 未结 8 1961
说谎
说谎 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 01:58

    var elem = document.getElementById('mytest1');
    
    // Simulate clicking on the specified element.
    triggerEvent( elem, 'click' );
    
    /**
     * Trigger the specified event on the specified element.
     * @param  {Object} elem  the target element.
     * @param  {String} event the type of the event (e.g. 'click').
     */
    function triggerEvent( elem, event ) {
      var clickEvent = new Event( event ); // Create the event.
      elem.dispatchEvent( clickEvent );    // Dispatch the event.
    }
    

    Reference

    • https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
    • https://codepen.io/felquis/pen/damDA

提交回复
热议问题