How to click a link from javascript

后端 未结 3 696
时光取名叫无心
时光取名叫无心 2020-12-12 04:46

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done?

Thanks

相关标签:
3条回答
  • 2020-12-12 05:14

    With JQuery It would be like this.

    $("#YOUR_A_TAG_ID").click();
    

    This only fires the function assigned to the click event. It will not navigate to the path specified in the href attribute.

    JQuery documentation for click

    0 讨论(0)
  • 2020-12-12 05:36
    window.onload = function() {
      var myLink = document.getElementById("YOUR_A_TAG_ID");
      fireClick(myLink);
    };
    
    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();
      }    
    }
    
    0 讨论(0)
  • 2020-12-12 05:41

    Another way is using JQuery's trigger feature.

    <span onmouseover="$('#alink').trigger('click');">Hello World</span>
    
    <a href="http://someurl" id="alink">A Link</a>
    
    0 讨论(0)
提交回复
热议问题