我有五个具有各自值的字段:
var valOne = document.getElementById("one").value;
var valTwo = document.getElementById("two").value;
var valThree = document.getElementById("three").value;
var valFour = document.getElementById("four").value;
var valFive = document.getElementById("five").value;
现在,如果我只想为填充值设置条件,例如 valOne
和 valTwo
不为空而其他为空,则:
if(valOne == "1" && valTwo == "2")
{
alert("match found");
}
如果valOne
和valThree
和valFour
不为空而其他两个为空,则相同,则:
if(valOne == "1" && valThree == "2" && valFour == "4")
{
alert("match found");
}
请注意,如果 valOne
不为空,则只会出现 1 个值与其给定值进行比较。
对于valOne
、valTwo
、valThree
、valFour
,1,2,3,4,5的含义是固定的>,valFive
.
我擅长 JavaScript,所以一个简单的线索对我来说确实很有帮助。
最佳答案
我建议你使用这样的方法
function isValid( idArray, validValueArray )
{
for( var counter = 0; counter < idArray.length; counter++)
{
var elem = document.getElementById( idArray[ counter ] );
var value = elem ? elem.value : "";
if ( value && value.length > 0 && value != validValueArray[ counter ] )
{
return false;
}
}
return true;
}
isValid( [ "one", "two", "three", "four" ], [ "1", "2", "3", "4" ] );
或者您可以按照键和值传递 id 和值
var keyValues = {
"one" : "1",
"two" : "2",
"three" : "3",
"four" : "4"
}
isValid( keyValues );
function isValid( keyValues )
{
for( var id in keyValues )
{
var elem = document.getElementById( id );
var value = elem ? elem.value : "";
if ( value && value.length > 0 && value != keyValues [ id] )
{
return false;
}
}
return true;
}
关于javascript - 如何在 JavaScript 中比较变量并过滤空白值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35569345/