简体   繁体   中英

How to add an onclick but don't execute href=“url” in a <a> tag?

I want to add an onclick function to an <a> tag where the onclick will run and the href won't. I have read that all you need to do is add return false; to the onclick function like so:

 <a href="https://google.ca" onclick="alert(1); return false;">click here!</a> 

This should create an alert dialog and not jump to google (or so I've been told), but for me it doesn't show the alert dialog and goes right to google. I have also tried return true; but the same thing happened.

The scenario is that a user enters whatever they would like into a textbox (can contain a whitelisted set of HTML tags including <a> ). After they press enter, it takes them to a new page and the HTML is reflected on this page. I want to see if they can enter a link to a possibly malicious website using the onclick, instead of going to the href.

EDIT:

When I inspect the link, this is all that shows up:

<a href="https://google.ca" rel="nofollow">click here!</a>

Nothing about the onclick function and the alert. Why did it strip out the onclick?

This snippet worked for me as well. It's something to do with the web app I'm using and I'm trying to figure out if there's something that could possibly be blocking this onclick from running

you can try

<a href="http://google.com" onclick="alert_func()">

function alert_func(){
    alert(1);
    return false;
}

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