Javascript and Anchor Tags, Best Practice?

后端 未结 5 690
梦如初夏
梦如初夏 2021-01-04 02:17

Quick Question.

Should we put Javascript in the HREF or use onClick (event)?

Are there any pros/cons to using either one. Personally I think it\'s easier/cle

5条回答
  •  既然无缘
    2021-01-04 03:06

    I would personally not put the JavaScript code in the HTML. You should use an event listener that will get triggered when the is clicked on.

    Click Me
    

    And then:

    document.getElementById('linkA').addEventListener('click', function(e){
        e.preventDefault(); // Prevents page from scrolling to the top
        alert('foo!');
    });
    

提交回复
热议问题