4

我的问题是,即使我单击Cancel确认中的按钮,链接仍会导航到其目的地?cancel如果用户在确认框中单击,我如何阻止链接导航到目的地?我只希望它在用户单击OK按钮时导航:

<a id='teachlogout' href='./teacherlogout.php'>Logout</a>
function logoutHandler() {
    if (confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n")) {
        return true;
    }
}

// logout link
$('#teachlogout').click(function() {
    logoutHandler();
});
4

4 回答 4

8

您需要return false或者event.preventDefault()如果用户取消了confirm. 尝试这个:

function logoutHandler() {
    return confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n");
}

// logout link
$('#teachlogout').click(logoutHandler); 
// ^ Shorter version when you only need to call 1 function with no params

或这个:

function logoutHandler(e) {
    if (!confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n")) {
        e.preventDefault();
    }
}

// logout link
$('#teachlogout').click(function(e) {
    logoutHandler(e);
}); 
于 2013-01-09T09:16:06.490 回答
3

您必须返回 false 才能停止导航。您可以简单地返回您从确认中获得的内容。

function logoutHandler() {
        return confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n"))
}

$('#teachlogout').click(function() {
      return logoutHandler();
});

如果您在 logoutHandler 中只有一个确认,则将其放入 click 事件中。

$('#teachlogout').click(function() {
        return confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n"))
});

您也可以使用event.preventDefault()来停止导航。

$('#teachlogout').click(function(event) {
       if(!confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n")))
           event.preventDefault();
});
于 2013-01-09T09:15:06.010 回答
2

将您的声明更改为:

return confirm("You are currently...");

问题是,当用户取消对话框时,您不会返回 false。

此外,您不使用处理程序中的返回值:

$('#teachlogout').click(function() {
    return logoutHandler(); // return was missing here
});
于 2013-01-09T09:14:52.970 回答
1

http://jsfiddle.net/hWe4E/

function logoutHandler() {
            if (confirm("You are currently creating an Assessment, are you sure you want to logout?" + "\n" + "(Your current assessment details will be lost)" + "\n")) {
                return true;
            }

  return false;  //added
}


//you need to return the true/false
$('#teachlogout').click(function() {
      return  logoutHandler();
});
于 2013-01-09T09:21:14.920 回答