我的问题是,即使我点击确认中的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();
});
答案 0 :(得分: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);
});
答案 1 :(得分: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中进行了确认,则将其置于点击事件中。
$('#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();
});
答案 2 :(得分:2)
将您的陈述更改为:
return confirm("You are currently...");
问题是,当用户取消对话框时,您不会返回false。
此外,您不使用处理程序中的返回值:
$('#teachlogout').click(function() {
return logoutHandler(); // return was missing here
});
答案 3 :(得分:1)
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();
});