Javascript:"else if"是否存在限制?陈述? [英] Javascript: Is there a limit to "else if" statements?

查看:55
本文介绍了Javascript:"else if"是否存在限制?陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文本字段中获得价值.我有一个if和另外几个if语句.

I am getting value from a text field. I have one if and several else if statement.

即使条件为真,问题也无法执行.

The problem the last else if doesn't execute even if the condition is true.

如果我将最后一个else更改为if,则执行后会发出警报.当我不执行该语句时,将其更改回else.否则的话,否则就可以了,因为它是在特定条件下触发/执行的.

If I change the last else if to if it executes and gives alert. When I change that back to else if the statement doesn't execute. The else if before that is fine as it's firing/executing on a particular condition.

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 ,那么满足以下条件之一:

The problem is that if txtVal.length > 11, then either this is met:

    else if(txtVal.indexOf("%") != -1)

或者满足:

    else if(( txtVal.length  >0) &&  (txtVal.indexOf("%") == -1))

因此它将永远不会达到 else if(txtVal.length> 11).您需要更改此内容:

So that it will never reach the else if( txtVal.length > 11 ). You need to change this:

    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)的情况.

so that it doesn't "capture" the case where txtVal.indexOf('%') == (txtVal.length-1).

这篇关于Javascript:"else if"是否存在限制?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆