我如何停止重复执行alert()在javascript中的if语句?



var inputs = document.querySelectorAll('.credentials input');
function checkCredentials(){
inputs.forEach(function(input){

if(input.value=="" && !alert('please enter a valid card number')){

alert('please enter a valid card number'); 

}
else{        
alert("payment successful");

}

})
}
<div class="card-container">

<div class="card-img">
<img src="visa.png">
</div><!-- card img -->
<div class="credentials">

<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="text" name="4">
<input type="text" name="5" class="fifth-input">
<input type="text" name="6">
<input type="text" name="7">
<input type="text" name="8">
<input type="text" name="9" class="ninth-input">
<input type="text" name="10">
<input type="text" name="11">
<input type="text" name="12">
<input type="text" name="13" class="thirteenth-input">
<input type="text" name="14">
<input type="text" name="15">
<input type="text" name="16">
</div><!-- credentials -->
<div class="btn">
<button onclick="checkCredentials();">Click to Proceed</button>
</div><!-- btn -->    
</div><!-- card container -->

我有16个输入,每个输入字段最多一个数字,我想要的是,点击一个按钮-如果任何输入字段为空,一个警告框说,"请输入一个有效的卡号必须显示"一次,页面被重新加载。-else显示"付款成功"的警告框一次,页面重新加载。

你可以试试:

var inputs = document.querySelectorAll('.credentials input');
let numberVar;
function checkCredentials(){
numberVar = 0;
inputs.forEach(function(input){
if(input.value=="" && numberVar++ < 1){ 
alert('please enter a valid card number');
}else{        
alert("payment successful");
}    
})
}

但是,如果您需要遍历所有输入并显示未填充的值,则需要使用不同的方法。并且表达式也需要用同样的方式重写。

您可以根据给定的条件筛选Array,并检查Array是否为空。我还建议使用函数的输入参数,而不是使用全局变量=)

的例子:

function checkCredentials(inputs){
const containsEmptyInputs = inputs.filter(i => i == "").length > 0;
const message = containsEmptyInputs ? 'please enter a valid card number' : 'payment successful';
alert(message);
}

最新更新