html - Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"? -
the following 2 methods of building link has sole purpose of running javascript code. better, in terms of functionality, page load speed, validation purposes, etc.?
function myjsfunc() { alert("myjsfunc"); } <a href="#" onclick="myjsfunc();">run javascript code</a> or
function myjsfunc() { alert("myjsfunc"); } <a href="javascript:void(0)" onclick="myjsfunc();">run javascript code</a>
i use javascript:void(0).
three reasons. encouraging use of # amongst team of developers inevitably leads using return value of function called this:
function dosomething() { //some code return false; } but forget use return dosomething() in onclick , use dosomething().
a second reason avoiding # final return false; not execute if called function throws error. hence developers have remember handle error appropriately in called function.
a third reason there cases onclick event property assigned dynamically. prefer able call function or assign dynamically without having code function 1 method of attachment or another. hence onclick (or on anything) in html markup this:
onclick="somefunc.call(this)" or
onclick="somefunc.apply(this, arguments)" using javascript:void(0) avoids of above headaches, , haven't found examples of downside.
so if you're lone developer can make own choice, if work team have either state:
use href="#", make sure onclick contains return false; @ end, called function not throw error , if attach function dynamically onclick property make sure not throwing error returns false.
or
use href="javascript:void(0)"
the second easier communicate.
Comments
Post a Comment