[英]Form field validation using switch case inside for loop in javascript
在我的 HTML 中,我創建了一個具有兩個屬性的表單 - item name
和item price
以及一個按鈕,其onclick()
事件將調用 javascript function temp()
。 下面是我附上的 javascript 代碼:
function temp(){
var a = 2
var b = 4;
var f = [a,b];
for(var i = 0; i <= f.length-1;i++)
{
switch(f[i])
{
case f[0]:
if (f[0] == 2) {
alert("hell");
}
break;
case f[1]:
if (f[1] == 4) {
alert("hello");
}
break;
}
}
當我單擊一個按鈕時,這會正確顯示兩個警報消息 - “地獄”和“你好”。 問題在於以下代碼:
function temp() {
var a = document.form1.item_name.value;
var b = document.form1.price.value;
var f = [a,b];
for(var i = 0; i <= f.length-1;i++)
{
switch(f[i])
{
case f[0]:
if (f[0] == "") {
alert("hell");
}
break;
case f[1]:
if (f[1] == "") {
alert("hello");
}
break;
}
}
}
此代碼兩次警告“地獄”,但如何?
The reason is that your first switch case of f[0] is always going to be satisfied and alert 'hell'
this works as anticipated:
switch(i)
{
case 0:
if (f[0] == "") {
alert("hell");
}
break;
case 1:
if (f[1] == "") {
alert("hello");
}
break;
}
}
您的開關盒的工作方式如下:-
switch("")
{
case ""
Alert hell
break
case ""
Alert hello
break
}
所以你的第一個案例每次都很滿意。 也不要混淆開關,如果一起使用,請使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.