How to simulate a click with JavaScript?

前端 未结 8 2001
说谎
说谎 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:04

    The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'.

    So, I changed the document.createEvent to 'MouseEvents' and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.

    function eventFire(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent(etype, true, false);
        var canceled = !el.dispatchEvent(evObj);
        if (canceled) {
          // A handler called preventDefault.
          console.log("automatic click canceled");
        } else {
          // None of the handlers called preventDefault.
        } 
      }
    }
    

提交回复
热议问题