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.

+5
source share
10 answers

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, , .

+18

false onclick. . foo() :

function foo() {
  // ... do stuff
  return false;
}

- , HTML :

<a href="#" onclick="return foo()">Click</a>

HTML:

<a href="#" onclick="foo(); return false;">Click</a>
+6

-, 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();
    }
}
+3

href="#" , . :

<a href="javascript:foo()">clicky</a>

( ). , Prototype ( JQuery .):

<a id="foo" href="#">clicky</a>

$('foo').observe('click', function(evt) { 
  foo();
  evt.stop(); // keeps it from navigating to the href url
}); 
+2
<a href="javascript: foo()" >Click</a>
0

false foo()

0

, - : 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>
0

<a href="#">Click</a>

IE6.

, .

<a href="#MAGIC">Click</a>

.

-1

return false;

onclick, . :

<a href="#" onclick="foo();return false;">Click</a>

:

function foo() {
  // other stuff
  return false;
}
-2

href javascript. :

<a href="javascript:foo()">Click</a>

, CSS: .

-2
source

All Articles