使用if / else语句将JS(jQuery)中的和/或运算符组合在一起

时间:2017-05-23 08:19:29

标签: jquery if-statement

我在jQuery if / else语句中将&&||运算符组合在一起时遇到了问题。这是一个例子

if(($x == 'on') && ($y !== 'on' || $z !== 'on')){

// it does not seem to work

}

但是,如果我只放置其中一个,它就可以了。实施例

if($x == 'on' && $y !== 'on' ){

// it works but I want to combine more like the above 
}

1 个答案:

答案 0 :(得分:0)

根据您的要求并根据评论" $ x必须为true且$ y OR $ z OR $ anyThing不正确"。您可能需要添加额外的代码行。

请参考以下代码并进行测试。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){       
        $('#testBtn').on('click', function(){           
            var xInput = $('#xInput').val(),
            yInput = $('#yInput').val(),
            zInput = $('#zInput').val();

            if(xInput == 'true' && (yInput == 'false' && zInput == 'false')){               
                $('#result').text("X it 'true'; Y & Z are 'false'");
            } else if(yInput == 'true' && (zInput == 'false' && xInput == 'false')){                
                $('#result').text("Y it 'true'; X & Z are 'false'");
            } else if(zInput == 'true' && (yInput == 'false' && xInput == 'false')){                
                $('#result').text("Z it 'true'; X & Y are 'false'");
            } else {
                $('#result').text("Try Again...");
            }
        });
    });
</script>
</head>
<body>
       X: <input type="text" id="xInput"> &nbsp 
       Y: <input type="text" id="yInput"> &nbsp 
       Z: <input type="text" id="zInput"> &nbsp  
       <br/>
       <br/>
       <button id="testBtn">Test If Condition</button>
       <br/>
       <br/>
       Result: <span id="result"></span>
</body>
</html>