【问题标题】:prompt function does not accept input which only contains numbers提示功能不接受仅包含数字的输入
【发布时间】:2021-06-28 06:07:11
【问题描述】:

我已添加确认对话框以再次输入我在提交之前获得的状态。

那个公园有效。 问题是prompt() 函数除了输入数字之外没有?

无论如何我可以添加该部分以便它可以通过吗?

$(".delete-status").click(function (ev, el) {

    var status = $(this).data("status");
    var statusInput = prompt("Confirm deletion by entering the status:");

    if (statusInput === status) {

        statusDelete(status);
    } else if (statusInput === null || statusInput === "") {

        alert("Field should not be empty!");
    } else {

        alert("Entered status and status don't match!");
    }
});

知道如何修复代码吗?我对 jQuery 和 JS 很陌生。谢谢

我想涵盖这两种情况。带字符串和带数字。

【问题讨论】:

  • prompt() 返回一个字符串。 status 是一个整数。由于您使用严格相等,因此它们不匹配。
  • 您检查用户输入的内容并循环,直到他们输入有效数据(但需要某种方式退出)。或者,使用不同的组件,例如模态对话框或第 3 方“提示”组件。 prompt() 将始终是未经验证的文本输入,它仅作为简单站点/概念验证的基本 UI 组件。

标签: javascript jquery integer prompt


【解决方案1】:

您可以将statusInput 字符串转换为数字。

这可能会更好,但大致如下:

$(".delete-status").click(function (ev, el) {
    var status = $(this).data("status");
    var statusInput = prompt("Confirm deletion by entering the status:");

    if (Number(statusInput) === Number(status)) {
        statusDelete(status);
    } else if (statusInput === null || statusInput === "") {
        alert("Field should not be empty!");
    } else {
        alert("Entered status and status don't match!");
    }
})

【讨论】:

  • 是的,但我认为这将是一个问题,因为我想涵盖这两种情况。带字符串和数字.. @MikeW
【解决方案2】:

jQuery 的.data() 方法会自动将数据解析为 JSON,因此如果它看起来是数字,它将返回一个数字,而不是字符串。

prompt() 始终返回一个字符串(如果您取消,则返回 null)。

所以你需要将statusstatusInput 转换为相同的类型,如果你想将它们与=== 进行比较。您可以使用parseInt() 将用户输入转换为整数。

$(".delete-status").click(function(ev, el) {

  var status = $(this).data("status");
  var statusInput = parseInt(prompt("Confirm deletion by entering the status:"));

  if (statusInput === status) {

    statusDelete(status);
  } else if (statusInput === null || statusInput === "") {

    alert("Field should not be empty!");
  } else {

    alert("Entered status and status don't match!");
  }
});

【讨论】:

  • 感谢重播。如果我在所有情况下都使用 parseInt 会影响状态是否只是字符串? @Barmar
  • 只有在希望用户输入数字时才应该使用它。
  • 另一种方法是将status 转换为字符串:$(this).data("status").toString()
  • 如果$(this).data("status")字符串,那么提示的parseInt()将不匹配
  • 其他替代方案:if (statusInput == status)(尽管通常人们推荐===,因为如果您不知道自己在做什么,== 可能会导致错误)(尽管有证据表明“=== " 似乎会导致更多错误...)
猜你喜欢
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2010-12-17
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 2016-09-20
相关资源
最近更新 更多