How to simulate a click with JavaScript?

前端 未结 8 1964
说谎
说谎 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:14
    document.getElementById('elementId').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));
    

    Follow this link to know about the mouse events using Javascript and browser compatibility for the same

    https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#Browser_compatibility

    0 讨论(0)
  • 2020-11-22 02:15

    Here's what I cooked up. It's pretty simple, but it works:

    function eventFire(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
      }
    }
    

    Usage:

    eventFire(document.getElementById('mytest1'), 'click');
    
    0 讨论(0)
提交回复
热议问题