【问题标题】:Confirm dialog box in javascript and htmljavascript和html中的确认对话框
【发布时间】:2024-01-23 05:39:01
【问题描述】:

我正在尝试在我的代码中包含一个确认对话框,但在实现它时遇到了困难。 我想在我的代码中添加一个按钮,点击它我会得到一个确认对话框。按“是选项”它应该删除我的数据库中的数据,而按“无选项”应该关闭对话框,什么都不做。 但实际上,当我运行我的代码时,我得到我的对话框和确认是/否选项,但运行“否选项”时,html 中的提交代码也会被触发,因此通过选择“是”或“否”我得到同样的效果,它总是从我的数据库中删除数据。

这是我的html代码:

<form method="POST" action="/delete/prop" >
<p class="card-text h6"> <b>Typology: </b> <%= book.typology %> </p>
<input type="hidden" name="id5" value=<%= book.id %> />
<input type="hidden" name="prop" value= "typology" />

<input type="submit" value="Yes" class="button btn btn-danger" onclick="confirmAction()" />
</form>

和我的javascript相关的对话代码:

<script type="text/javascript">
  function confirmAction() {
    let confirmAction = confirm("Are you sure to execute this action?");
    if (confirmAction == true) {
      alert("Action successfully executed");
    } else {
      alert("Action cancelled");
    }
  }

【问题讨论】:

  • 我不知道“否”选项在哪里,你能发布更多代码吗?
  • 不确定,但我认为您应该从 confirmAction() 函数返回 false 以取消提交。
  • @AndreiTornea。感谢您的评论,但不幸的是,此操作不再涉及代码。 confirm() 函数应该自己生成是/否选项。
  • @TsahiAsher。谢谢您的建议。我也尝试返回 false,但我得到了相同的结果。数据在返回 false 时也被删除,而不是希望我需要应用程序执行,即在这种情况下什么也不做。

标签: javascript html dialog


【解决方案1】:

我在@anavega 发布的another website 中找到了解决方案。

她提到我错过了html中的return元素。

这里有一个例子来测试它:

function confirmAction() {
    let confirmAction = confirm("Are you sure to execute this action?");
    if (confirmAction == true) {
      alert("Action successfully executed");
    } else {
      alert("Action cancelled");
    }
}
&lt;input type="submit" value="Yes" class="button btn btn-danger" onclick="return confirmAction()" /&gt;

感谢您的帮助!

【讨论】:

  • 但是你的函数没有返回任何东西(或者就 JS 而言,返回一个假值)。如果用户点击是,它会起作用吗?
最近更新 更多