简体   繁体   中英

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.

you need to pass in the event if you wish to preventDefault.

html:

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

script:

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

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:

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

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

See the problem?

My runFunction is 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:

link.onclick = runFunction;

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):

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;    
}

When I plugged your code into chrome, I got this as the error in the console: Uncaught TypeError: Cannot read property 'srcElement' of undefined

IF the javascript bombs out while processing, it never gets a chance to return at all so the browser tends to disregard what is in the onclick handler after the exception.

Since it bombed out... default behavior of anchor tags, which is to send you off to wherever the href says to go.

Try wrapping the contents of the function in a try/catch block and see what turns up if this kind of thing plagues you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM