1

我的页面上有一个锚点,如下所示:<a id="login" href="login.php"></a>

但是,当用户在页面中输入数据时,为了在进入登录页面时不会丢失该数据(无需登录即可保存数据),我通过取出 href 并添加一个onclick 警告用户,如下:

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

所以用户收到警告,现在他可以再次点击登录按钮登录。

由于某种原因,我遇到的问题$('#login').attr('href','login.php');使页面立即重定向。我猜这是因为我们仍然处于锚点点击的中间。

如何更改此 href 但在再次单击按钮之前阻止页面实际重定向?我尝试添加return false,但没有帮助。

提前致谢!

4

2 回答 2

1

为什么不将其合并为一个项目?

$('#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');
    }
});

这将在第一次阻止该操作,提供警报,并为其提供clicked数据以显示它已被单击。第二次不满足if条件,继续登录。

这避免了javascript:void(0)位以及任何onclick属性……所有内容都包含在您的 JS 文件中。

于 2013-06-13T19:34:52.693 回答
0

你需要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."); 
    }
});
于 2013-06-13T19:34:57.630 回答