简体   繁体   中英

stop anchor from redirecting when dynamically setting href

I have an anchor on my page which looks like this: <a id="login" href="login.php"></a>

However, when a user inputs data in the page, in order that he shouldn't lose that data when going to the login page (the data can be saved without being logged in), I change it by taking out the href and adding an onclick to warn the user, as follows:

if (-code which checks for user input-){
        $('#login').attr('href','javascript:void(0)');$('#login').attr('onclick','logincheck()');
        }
function logincheck(){
alert("Going to the login page will make you lose your work. If you want to save them to a collection, please do so now. When you're ready, click the login button again."); 
$('#login').attr('onclick','');$('#login').attr('href','login.php');
}

So the user gets the warning, and now the he can click the login button again to login.

The problem I'm having that for some reason the $('#login').attr('href','login.php'); makes the page redirect right away. I'm guessing this is because the we're still in the middle of the anchor click.

How can I change this href but keep the page from actually redirecting before the button is clicked again? I tried adding return false but that didn't help.

Thanks in advance!

Why not consolidate it into a single item?

$('#login').on('click',function(e){
    if($(this).data('clicked')!=='true'){
        e.preventDefault();
        alert("Going to the login page will make you lose your work. If you want to save them to a collection, please do so now. When you're ready, click the login button again.");
        $(this).data('clicked','true');
    }
});

This will prevent the action the first time, provide the alert, and give it the clicked data to show it has been clicked. The second time it won't meet the if condition, and continue to login.

This avoids the javascript:void(0) bit, as well as any onclick attributes ... everything is contained in your JS file.

You need e.preventDefault();

$('#login').on('click', function(e){
    if(!$(this).data('clicked')){
            $(this).data('clicked', true);
            e.preventDefault();
            alert("Going to the login page will make you lose your work. If you want to save them to a collection, please do so now. When you're ready, click the login button again."); 
    }
});

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