2017-05-23 99 views
0

我在将jQuery if/else语句中的&&||运算符组合在一起时遇到问题。这里是一个例子在JS(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

究竟是什么要求?我建议你花一些时间在基础知识上 – Satpal

+0

第一个。我需要检查一个变量是否为真,以及一组变量是否为真。例如。 $ x必须为真并且$ y OR $ z OR $ anyThing不为真 – Ayanize

+0

'if(($ x ==='on')&&!($ y ==='on'|| $ z === '')')){'这可能不正确,但这更符合我如何去做。无论如何, 需要更多细节。 –

回答

0

根据您的要求和根据注释“$ x必须为真,$ 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>