Javascript and Anchor Tags, Best Practice?

后端 未结 5 689
梦如初夏
梦如初夏 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

    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"); };
    

提交回复
热议问题