Hit This is my javascript file func...">

Inline javascript onclick event

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.

+5
source share
3 answers

To link both very correct answers together, what happened was that you entered a function in which you wrote onclick="return runFunction();"

If you look at it, what it really does is like this:

var link = document.getElementById("myLink");

link.onclick = function () { runFunction(); };

See the problem?

Mine runFunctionis called without any event object passed at all. ... which means it var thisLink = (evt) ?will return false, which means that it will try to run in oldIE mode.

Writing onclick="runFunction"is the same as saying:

link.onclick = runFunction;

This means that when the onclick event occurs, runFunction is called, and an event object will be sent in browsers compatible with W3C.

.

- JavaScript JavaScript HTML HTML, , .

, , , :

W3C (, ):

function runFunction (evt) {

    // stops the default-action from happening
    // means you need to find another way to fire it, if you want to later
    evt.preventDefault();


    // stops higher-up elements from hearing about the event
    // like if you stop a submit button from "clicking", that doesn't stop the form
    // from submitting
    evt.stopPropagation();

    //the oldIE versions of both of these are
    event.cancelBubble = true;
    event.returnValue = false;    
}
+8

, .

HTML:

<a href="#" onclick="runFunction(event)">Hit</a>

script:

function runFunction (evt) {
    evt.preventDefault();
    evt.stopPropagation();
}
+7

chrome, : Uncaught TypeError: 'srcElement' undefined

javascript , , , , , onclick .

... , , href.

Try wrapping the contents of the function in a try / catch block and see what happens if you care.

0
source

All Articles