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>

谢谢


智慧大石
浏览 317回答 3
3回答

慕桂英546537

您必须将点击事件“终止”到 a 标签,为此,您必须将事件对象传递给OnClickNextPage函数,然后调用.preventDefault()该事件。return false;动作不影响onclick事件。HTML<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage(event);">Test</a>Javascriptfunction OnClickNextPage(event) {&nbsp; var result = confirm("Are you sure ?");&nbsp; if (!result) {&nbsp; &nbsp; event.preventDefault(); // prevent event when user cancel&nbsp; }&nbsp; // go to page in a tag's href when user choose 'OK'}

蝴蝶刀刀

尝试&nbsp; function OnClickNextPage(e){e.preventDefault();&nbsp; &nbsp; &nbsp;var result = confirm("Are you sure ?");&nbsp; &nbsp; &nbsp; if (!result) {&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}编辑 -对不起,我的错,问题是你在 href 中调用页面加载事件,最终触发 DOM 的优先级<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage();">Test</a>像这样试试&nbsp;<a href="#" onclick="OnClickNextPage();">Test</a>function OnClickNextPage(e){&nbsp; &nbsp;e.preventDefault();&nbsp; &nbsp; var result = confirm("Are you sure ?");&nbsp; &nbsp; &nbsp; if (!result) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;window.location.href = [[Your URL Here]]&nbsp; &nbsp; &nbsp; }&nbsp;}

慕雪6442864

您必须使用 preventDefault() 函数来阻止事件的默认行为,而不是返回 false。这是代码<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage();">Test</a>function OnClickNextPage(event){&nbsp; var result = confirm("Are you sure ?");&nbsp; if (!result) {&nbsp; &nbsp; &nbsp;event.preventDefault();&nbsp; &nbsp;}&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript