What is the correct way to change the behavior of the <a> tag?
I want the link to call the Javascript function through the onclick event and not do anything (follow the link). What is the best way to do this? I usually do this:
<a href="#" onclick="foo()">Click</a>
But I'm not sure if this is the best way, in which case it is looking at page.html #, which is bad for what I am doing.
Usually, you should always have a return link to make sure that clients with JavaScript disabled still have some features. This concept is called unobtrusive JavaScript. Example ... Say you have the following search link:
<a href="search.php" id="searchLink">Search</a>
You can always do the following:
var link = document.getElementById('searchLink');
link.onclick = function() {
try {
// Do Stuff Here
} finally {
return false;
}
};
, javascript search.php, JavaScript .
:. nickf, # 2, , .
-, href - , , href, '#', href "javascript:;"
-, JavaScript , . , , - :
window.onload = {
var myLink = document.getElementById('myLinkID');
myLink.onclick = function(evt) {
var evt = (evt) ? evt : ((event) ? event : null); // for cross-browser issues
evt.preventDefault();
evt.stopPropagation();
foo();
}
}
, - : hover -css-...
a, - -...
, , -: hover, , W3C , , html; html, css javascript.
, , , ! -)
, , , onclick-event return false, ...
, , javascript:
<a href="http://en.wikipedia.org/wiki/Css" target="_blank" onclick="window.open(this.href,'_blank','width=600,height=450,status=no');return false;">Show wikipedia css</a>