我让 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>
我修改了两个警报“我们有它”和“我们没有”
这段代码有什么问题?
最佳答案
你需要改变逻辑,你需要看看它是否存在并查看所有这些。您不应该对每个索引都发出警报。
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 ");
}
关于javascript - js验证同时发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898572/