HTML anchor link - href and onclick both?

后端 未结 4 1995
耶瑟儿~
耶瑟儿~ 2020-11-28 21:38

I want to author an anchor tag that executes some JavaScript and then proceeds to go wherever the href was taking it. Invoking a function that executes my JavaS

相关标签:
4条回答
  • 2020-11-28 22:07

    When doing a clean HTML Structure, you can use this.

    //Jquery Code
    $('a#link_1').click(function(e){
      e . preventDefault () ;
      var a = e . target ;
      window . open ( '_top' , a . getAttribute ('href') ) ;
    });
    
    //Normal Code
    element = document . getElementById ( 'link_1' ) ;
    element . onClick = function (e) {
      e . preventDefault () ;
      
      window . open ( '_top' , element . getAttribute ('href') ) ;
    } ;
    <a href="#Foo" id="link_1">Do it!</a>

    0 讨论(0)
  • 2020-11-28 22:08
    <a href="#Foo" onclick="return runMyFunction();">Do it!</a>
    

    and

    function runMyFunction() {
      //code
      return true;
    }
    

    This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

    0 讨论(0)
  • 2020-11-28 22:19

    If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false.

    If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

    As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.

    0 讨论(0)
  • 2020-11-28 22:22

    Just return true instead?

    The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

    0 讨论(0)
提交回复
热议问题