JavaScript确认取消按钮无法停止JavaScript

15

我有一个与某些页面上的评论相关联的删除按钮。 当您单击删除按钮时,我尝试弹出确认对话框,询问您是否确定要删除该评论。 点击“确定”应运行删除评论的函数,而点击“取消”不应运行该函数,而只是关闭对话框。

这是我的代码:

onclick="confirm('Are you sure that you want to delete this comment?'); commentDelete(1);"

我的问题是:当我点击“取消”时,删除函数仍然会运行。 我猜测这是因为当我点击“取消”时,JavaScript仍在向前执行并调用该函数。 我该如何正确地完成这个操作? 我知道这可能是一个简单的问题。 谢谢任何帮助!

7个回答

21
onclick="if (confirm('Are you...?')) commentDelete(1); return false"

你缺少了一个if条件语句。在你的代码中,首先获取问题,然后不管回答是什么,都会调用commentDelete方法。


1
谢谢你的帮助!我知道这是一些基础的东西。+1给你! - RyanPitts

7

在头标签中你可以写入以下代码:

<script language="javascript" type="text/javascript">

    function getConfirmation()
    {
        var retVal = confirm("Do you want to continue ?");
        if (retVal == true)
        {
            alert("User wants to continue!");
            return true;
        } 
        else
        {
            alert("User does not want to continue!");
            return false;
        }
    }
</script>

在编写完这段代码后,您可以在以下代码中调用此函数:
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
    CommandName="Edit" Text="Edit" **OnClientClick="getConfirmation()"**>
</asp:LinkButton>

3
您正在处理 confirm,就像它是一个if语句,它只会返回一个布尔值true或false。
if(confirm('foo')){ alert('bar'); }

2
function confirmCancel(){
   var msj='Are you sure that you want to delete this comment?';
   if (!confirm(msj)) { 
      return false;
   } else {
      window.location='backcables.php';
   }
}

0

希望这能帮助到某个人。

var result = confirm("Are you sure");
return !!result;

-1
也许是因为您在包含 JavaScript 的表单中设置了 type=submit
如果您不希望在点击取消时提交,应将其设置为按钮、图像或其他内容。
<form name="form_name">
    <input type="button" onclick="javascript_prompt()" value="GO"/>
    <input type="hidden" name="new_name" value=""/>
</form>

Javascript prompt的示例:

function javascript_prompt(){
    var name = prompt("Tell me your name.", "");
    if (name != "" && name != null){
        document.form_name.new_name.value = name;
        document.form_name.submit();
    }else{
        return false;
    }
}

-1

你应该返回 false 以阻止默认事件。这应该可以工作:

onclick="confirm('Are you sure that you want to delete this comment?'); commentDelete(1);return false;"

真的,return false 没有出现,但这不是 OP 最大的问题。 - Amadan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接