Javascript 提示已取消,未在 While 循环中表现
我有一个提示,基本上是必填字段,不能包含小数。我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信问题出在您的
while
条件中 - 您正在执行 在所有条件上按位或|
。这意味着rmiles.indexOf(".")
始终被调用,即使rmiles
通过promptnull
也是如此代码> 单击“取消”时。这是因为按位或不会短路。尝试 逻辑 OR
||
短路,从而避免空引用错误:I believe the problem is in your
while
condition - you are doing bitwise OR|
on all the conditions. This means thatrmiles.indexOf(".")
is always called, even whenrmiles
is set tonull
byprompt
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:因为当用户单击“取消”时
rmiles
为 null...所以rmiles.indexOf
会产生错误/异常并终止循环。Because
rmiles
is null when the user clicks 'cancel'... sormiles.indexOf
produces an error/exception and kills the loop.