JavaScript确认取消按钮不停止JavaScript

Rya*_*tts 12 javascript confirm dialog

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

这是我的代码:

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

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

Ama*_*dan 17

onclick="if (confirm('Are you...?')) commentDelete(1); return false"
Run Code Online (Sandbox Code Playgroud)

你错过了if.在您的版本中,首先您会得到一个问题,然后无论答案如何,您都会打电话commentDelete.


小智 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>
Run Code Online (Sandbox Code Playgroud)

编写此代码后,您可以在以下代码中调用此函数:

<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
    CommandName="Edit" Text="Edit" **OnClientClick="getConfirmation()"**>
</asp:LinkButton>
Run Code Online (Sandbox Code Playgroud)