我将HTML表单发送参数发送到JavaScript以检查输入是否等于数组中的值然后发送警报消息但问题是函数在条件为真时发送两个警报
这是我的代码
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function test(){
var cars=["a","b","c"];
var c;
var inp=document.forms["form1"]["input1"].value;
for(c=0;c<cars.length;++c){
if(cars[c]===inp){
alert("we have it");
}else{
alert("we don't have ");
}
}
}
</script>
</head>
<body>
<form method="get" name="form1" onsubmit="return test()">
<input type="text" name="input1" />
<input type="submit" />
</form>
</body>
我修改了警告“我们拥有它”和“我们没有”
这段代码有什么问题?
答案 0 :(得分:2)
您需要更改逻辑,您需要查看它是否存在并查看所有逻辑。你不应该警惕每一个指数。
var inStock = false; //Use a boolean to hold state
for(c=0;c<cars.length;++c){
if(cars[c]===inp){ //see if it matches
inStock = true; //if it matches set Boolean to true
break; //exit loop (no reason to keep looking)
}
}
if(inStock) { //check the boolean to see if we found it
alert("we have it");
} else {
alert("we don't have ");
}
答案 1 :(得分:0)
只要在符合条件后添加退货......
function test(){
var cars=["a","b","c"];
var c;
var inp=document.forms["form1"]["input1"].value;
for(c=0;c<cars.length;++c){
if(cars[c]===inp){
alert("we have it");
return;
}else{
alert("we don't have ");
}
}
}