简体   繁体   English

循环内的Javascript提示

[英]Javascript Prompt inside loop

for (var j=0; j<2; j++){
listno=prompt("Enter Item Code","0");
listno = parseInt(listno);

if (listno > 0) {
    PRODUCT_WANT.push(PRODUCT_LIST[listno]);
    WANT_PRICE.push(PRICE_LIST[listno]);
}

else {
alert('Invalid Product Code');
}
if (quantno > 0) {
    quantno=prompt("Enter Quantity","0");
    quantno = parseInt(quantno);
    quantity.push(quantno);
}

else {
alert('Invalid Quantity');
}
}    

The loop works but I don't want to have to set the loop count I want to be able to put it to eg 999 then be able to press cancel on the prompt and have the loop finish 循环有效,但我不想设置循环计数,我希望能够将其设置为例如999,然后可以在提示符下按Cancel并完成循环

prompt will yield null if cancel is pressed. 如果按取消,则prompt将产生null。

You might do something like this: 您可能会执行以下操作:

while(listno = prompt("Enter Item Code", "0")) {
   ...
}

Edit . 编辑 The result of prompt will be whatever was written in the input prompt, or null if cancel was pressed. prompt的结果将是在输入提示中写入的内容;如果按了cancel,则返回null Since null will evaluate to false when used in a condition, you can use it in a while loop, to run some code while the prompt evaluates to true, ie keep prompting as long as a valid number is entered. 由于在某种情况下使用null它将评估为false ,因此可以在while循环中使用它,以在提示评估为true时运行一些代码,即,只要输入有效数字,就一直提示。

Demo 演示版

What you want is a while loop :) 您想要的是一个while循环:)

As an elaboration to Davids answer: What a while loop is doing is that the "body" of the while loop is executed, until a condition is meet. 大卫斯(Davids)的一个解释是:while循环的作用是执行while循环的“ body”,直到满足条件为止。 So first of, you want to have some condition that can evaluate to either true or false. 因此,首先,您需要具有一些条件,该条件可以评估为true或false。 If the condition is true, the "body" of the while loop is executed, and in the "body" you can change the condition. 如果条件为true,则执行while循环的“ body”,并且可以在“ body”中更改条件。 Giving an example 举个例子

var i = 0;
while(i < 20)
{
    i = i+1;
}

the above will run as long as i is smaller than 20. 只要我小于20,上面的代码就会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM