Javascript确认框,单击取消不起作用,页面仍然加载



我有一个项目使用确认框javascript,如果用户单击取消然后什么都不做,但页面仍然加载,我搜索所有关于确认框的信息,但我找不到我要找的东西,请帮我解决这个问题,这里有一些代码

JavaScript

function OnClickNextPage(){
var result = confirm("Are you sure ?");
if (!result) {
return false;
}
}

.html

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="return OnClickNextPage();">Test</a>

谢谢

而不是返回 false,你必须使用 preventDefault(( 函数阻止事件的默认行为。这是代码

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage();">Test</a>
function OnClickNextPage(event){
var result = confirm("Are you sure ?");
if (!result) {
event.preventDefault();
}
}

您必须将点击事件"终止"为 a 标签,为此,您已将事件对象传递给OnClickNextPage函数,然后对事件调用.preventDefault()return false;操作不会影响onclick事件。

.HTML

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage(event);">Test</a>

爪哇语

function OnClickNextPage(event) {
var result = confirm("Are you sure ?");
if (!result) {
event.preventDefault(); // prevent event when user cancel
}
// go to page in a tag's href when user choose 'OK'
}

试试

function OnClickNextPage(e){
e.preventDefault();
var result = confirm("Are you sure ?");
if (!result) {
return false;
}
}

编辑--

对不起,我的错,问题是您正在 href 中调用页面加载事件,该事件最终以 DOM 的优先级触发

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage();">Test</a>

像这样尝试

<a href="#" onclick="OnClickNextPage();">Test</a>
function OnClickNextPage(e){
e.preventDefault();
var result = confirm("Are you sure ?");
if (!result) {
return false;
} else {
window.location.href = [[Your URL Here]]
}
}

JS

function OnClickNextPage(e){
console.log('after prevent')
var result = confirm("Are you sure ?");
if (!result) {
e.preventDefault();
return false;
}
}

.HTML

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="return OnClickNextPage(event);">Test</a>

最新更新