简体   繁体   English

jQuery三元条件运算符中的多个条件

[英]Multiple conditions in jquery ternary conditional operator

I want to write ternary conditional operator in jquery where condition set by jquery variable. 我想在jquery中写三元条件运算符,其中条件由jquery变量设置。 My script toggle's class for particular condition only.In my script variable comes from other settings. 我的脚本切换仅适用于特定条件的类。我的脚本变量来自其他设置。

jquery: jQuery的:

<script type="text/javascript">
$(document).ready(function() {
  $("#my_div")
    .removeClass("horizontal vertical")
    .addClass( my_color == 'red'  ? 'horizontal' : 'vertical');
});
</script>

my_color is jquery variable which may have one value at a time from red,green,blue,black,white or silver . my_color是jquery变量,一次可能有一个值,从red,green,blue,black,white or silver

I want to set class horizontal if my_color is red, blue or green and class vertical for other three values. 如果my_color是红色,蓝色或绿色,我想将类设置为水平,将其他三个值设置为类垂直。 can anyone help me write simplified ternary operator for above jquery? 谁能帮我为上述jquery编写简化的三元运算符?

Use or operator in the condition part of the operator. 在操作员的条件部分使用或操作员。 You your would be 你会的

<script type="text/javascript">
  $(document).ready(function() {
    $("#my_div")
        .removeClass("horizontal vertical")
        .addClass( my_color == 'red' ||  my_color == 'blue' ||  my_color == 'green'  ? 'horizontal' : 'vertical');
  });
</script>
 $("#my_div")

If you have many color you can put them array and use that in condition. 如果您有很多颜色,则可以将它们放在数组中,并在适当的情况下使用它。

 $("#my_div")
 .removeClass("horizontal vertical")
 .addClass( ['red', 'blue', 'green', 'gray'].indexOf(my_color) != -1 ? 'horizontal' : 'vertical');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM