我从文本字段中获取值。我有一个 if 和几个 else if 语句。
即使条件为真,最后一个 else if 也不执行的问题。
如果我将最后一个 else if 更改为 if 它会执行并发出警报。当我将其改回 else 时,如果该语句不执行。之前的 else if 很好,因为它是在特定条件下触发/执行的。
function Valcheck()
{
var txtVal = document.getElementById("sometextField").value;
if(txtVal =="%")
{
alert("% is only allowed with other characters.");
return;
}
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
else if(txtVal.indexOf(",") != -1)
{
alert("Comma or comma separated values are not allowed.");
return;
}
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
{
alert("Please enter % at the end of the value.");
return;
}
else if( txtVal.length > 11 )
{
alert(" Value can't be greater than 11 characters.");
return;
}
}
请帮忙。谢谢
最佳答案
问题是,如果txtVal.length > 11
,那么要么满足:
else if(txtVal.indexOf("%") != -1)
或者满足:
else if(( txtVal.length >0) && (txtVal.indexOf("%") == -1))
这样它就永远不会到达else if( txtVal.length > 11 )
。您需要更改此设置:
else if(txtVal.indexOf("%") != -1)
{
if((txtVal.indexOf('%')) != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
}
对此:
else if(txtVal.indexOf("%") != -1 && txtVal.indexOf('%') != (txtVal.length-1))
{
alert(" % is only allowed at the end.");
return;
}
这样它就不会“捕获”txtVal.indexOf('%') == (txtVal.length-1)
的情况。
关于Javascript: "else if"语句有限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8812814/