Browser-friendly way to simulate anchor click with jQuery?

前端 未结 4 1720
一整个雨季
一整个雨季 2021-01-01 06:32

I\'m trying to simulate a click on an anchor tag using jQuery. I\'ve been digging around StackOverflow and Google for a while and haven\'t found anything that works on all o

4条回答
  •  余生分开走
    2021-01-01 07:13

    This should work...

    $(function() {
    
      fireClick($("a")[0]);
    
    });
    
    function fireClick(elem) {
      if(typeof elem == "string") elem = document.getElementById(objID);
      if(!elem) return;
    
      if(document.dispatchEvent) {   // W3C
        var oEvent = document.createEvent( "MouseEvents" );
        oEvent.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, elem);
        elem.dispatchEvent(oEvent);
      }
      else if(document.fireEvent) {   // IE
        elem.click();
      }    
    }
    

提交回复
热议问题