Javascript and Anchor Tags, Best Practice?

后端 未结 5 664
梦如初夏
梦如初夏 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 02:58

    In the onclick event (although assigned with JS rather then the attribute) with a sensible href attribute. Build on things that work

    0 讨论(0)
  • 2021-01-04 03:06

    1) Rather use onclick. Be sure to have a rational fallback URL in href when JS is not allowed.

    2) Rather than onclick="...", you should use event handler. Find elements using jQuery or XPath, and then for each, call element.addEventListener().

    element.addEventListener("click", function() { alert("bar"); }, false);
    

    Or the old way...

    element.onclick = function() { alert("foo"); };
    
    0 讨论(0)
  • 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 <a> is clicked on.

    <a href="#" id="linkA">Click Me</a>
    

    And then:

    document.getElementById('linkA').addEventListener('click', function(e){
        e.preventDefault(); // Prevents page from scrolling to the top
        alert('foo!');
    });
    
    0 讨论(0)
  • 2021-01-04 03:10

    Generally, I would externalize JavaScript but use thehref to call it:

    <a href="javascript:foo('bar!');">Click Me</a>

    Although I think your quick alert example is fine as an exception to the rule.

    However, if your using a JS library like jQuery you can of course assign events directly - see the first example in jQuery tutorial which looks at the anchor element http://docs.jquery.com/Tutorials:How_jQuery_Works

    0 讨论(0)
  • 2021-01-04 03:22

    Keeping the code separate from the html is cleaner IMO.

    <a id="foo" href="#">Click Me</a>
    

    Then in head or separate js file:

    document.getElementByID("foo").onclick = function() { alert("hi"); }
    
    0 讨论(0)
提交回复
热议问题