简体   繁体   中英

jQuery prevent anchor click

I'm trying to prevent the default anchor link and onclick event to trigger.

Here's the HTML code:

<a id="mylink" href="http://google.com" 
    onclick="window.location.href='http://google.com.au'; return false;">
Google</a>

I'm trying to prevent any redirects from occurring, using the following jQuery code:

$("#mylink").click(function(ev) {
    ev.preventDefault();
    ev.stopPropagation();
}

But it doesn't seem to work. The code still invokes the anchor onclick event and redirects to http://google.com.au

Any clues or suggestions? Thanks in advance.

只要 .click()回调之前调用它,您需要手动清除onclick

$("#mylink").prop('onclick', null);

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