This is my html code
<a href="#" onclick="return clickHandler()">Hit</a>
This is my javascript file
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
But when i click the Hit Link, it redirects.
To tie both of the very-correct answers together, what’s happened is you’ve inlined a function where you’ve written
onclick="return runFunction();"If you look at that, what it’s really doing is going like this:
See the problem?
My
runFunctionis being called without any event object passed in, at all.…which means that
var thisLink = (evt) ?is going to return false, which means that it’s going to try to run in oldIE-mode.By writing
onclick="runFunction", that’s the same as saying:Which means that when the onclick event happens, runFunction will be called, and in W3C-compliant browsers, it will be sent an event object.
Which is why that solution works.
The best way to avoid a lot of this confusion is to deal with JavaScript from inside of JavaScript, and to deal with HTML inside of HTML, so that you don’t have to worry about how strings translate into code.
Now, to get all of this to work, AND prevent redirection, you want to do this:
for W3C browsers (the ones that pass the event parameter):