14

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

这是我的代码:

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

我的问题:当我点击取消删除功能仍然运行。我的猜测是该函数仍在被调用,因为当我单击取消时,它只是在 JavaScript 中前进并调用该函数。我怎样才能正确地做到这一点?我知道这可能是一个简单的问题。谢谢你的帮助!

4

7 回答 7

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

你缺少一个if. 在您的版本中,首先您会收到一个问题,然后无论答案如何,您都会调用commentDelete.

于 2011-04-29T17:01:12.917 回答
7

在 head 标签中,您可以编写以下代码:

<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>
于 2014-04-23T12:51:22.473 回答
3

您正在处理确认是否是一个if语句,它只返回一个布尔值 true 或 false。

if(confirm('foo')){ alert('bar'); }
于 2011-04-29T17:01:34.163 回答
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';
   }
}
于 2013-05-19T23:48:41.937 回答
0

愿这对某人有所帮助。

var result = confirm("Are you sure");
return !!result;
于 2018-11-16T06:06:23.050 回答
-1

您应该返回 false 以防止默认事件。这应该有效:

onclick="confirm('Are you sure that you want to delete this comment?'); commentDelete(1);return false;"
于 2011-04-29T17:00:48.410 回答
-1

也许是因为您type=submit在包含javascript的表单中设置了。

如果单击取消后不想提交,则应将其设置为按钮或图像或其他任何内容

<form name="form_name">
    <input type="button" onclick="javascript_prompt()" value="GO"/>
    <input type="hidden" name="new_name" value=""/>
</form>

javascript 提示示例:

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;
    }
}
于 2012-09-22T23:13:27.057 回答