Javascript 提示已取消,未在 While 循环中表现

发布于 2024-12-09 14:17:37 字数 592 浏览 0 评论 0原文

我有一个提示,基本上是必填字段,不能包含小数。我有一个 while 循环,无论单击“确定”还是“取消”,它都应该继续提示用户输入信息,直到指示数字为止。只要单击“确定”按钮,一切都会正常工作。如果留空并单击“确定”,或者如果提供带小数的数字并单击“确定”,它将继续提示。但如果点击取消,则不会继续提示。

var rmiles = prompt("Please indicate actual miles driven for payroll");
    while (rmiles == null | rmiles == "null" | rmiles == " " | rmiles.indexOf(".") != -1) {
        alert("Mileage is required when arriving on site and can only be whole numbers.  No Decimals.  Please enter 0 if you did not intend to arrive on site.");
        rmiles = prompt("Please indicate actual miles driven for payroll");
    }

I have a prompt that basically is a required field and cannot contain a decimal. I have a while loop that should continue to prompt the user for information until a number is indicated regardless of whether OK or Cancel are clicked. Everything works fine as long as the OK button is clicked. It continues to prompt if left blank and OK is clicked or if a number with a decimal is provided and OK is clicked. But if cancel is clicked, it doesn't continue to prompt.

var rmiles = prompt("Please indicate actual miles driven for payroll");
    while (rmiles == null | rmiles == "null" | rmiles == " " | rmiles.indexOf(".") != -1) {
        alert("Mileage is required when arriving on site and can only be whole numbers.  No Decimals.  Please enter 0 if you did not intend to arrive on site.");
        rmiles = prompt("Please indicate actual miles driven for payroll");
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掀纱窥君容 2024-12-16 14:17:37

我相信问题出在您的 while 条件中 - 您正在执行 在所有条件上按位或 |。这意味着 rmiles.indexOf(".") 始终被调用,即使 rmiles 通过 promptnull 也是如此代码> 单击“取消”时。这是因为按位或不会短路。

尝试 逻辑 OR ||短路,从而避免空引用错误:

while (rmiles == null || /*...*/

I believe the problem is in your while condition - you are doing bitwise OR | on all the conditions. This means that rmiles.indexOf(".") is always called, even when rmiles is set to null by prompt when Cancel is clicked. This is because bitwise OR will not short-circuit.

Try the logical OR || which does short-circuit and thus avoids the null reference error:

while (rmiles == null || /*...*/
鯉魚旗 2024-12-16 14:17:37

因为当用户单击“取消”时 rmiles 为 null...所以 rmiles.indexOf 会产生错误/异常并终止循环。

Because rmiles is null when the user clicks 'cancel'... so rmiles.indexOf produces an error/exception and kills the loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文