一个jQuery’if’条件来检查多个值

在下面的代码中,有没有更好的方法来使用jQuery检查条件?

if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) 

除非有其他问题,比如你是否会重复使用#test1,…字段进行更多处理,你的应该是好的。

如果您再次获取任何值以执行某些操作,我建议将$(’#test1’)结果存储在变量中,这样您就不需要重新查询dom。

例如:

 var t1 = $('#test1'); if((t1.val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) { t1.val('Set new value'); } 

这也提高了行的可读性;)

 var values = ['first_value', 'second_value', 'third_value', 'fourth_value']; $('#test1, #test2, #test3, #test4').each(function(index, el) { if($.inArray(this.value, values)) { // do some job; return false; // or break; } }); 
 var c=0, b='#test', a=['first_value','second_value','third_value','fourth_value']; for(var i=0; i<4; i++) if($(b+i).val() == a[i]) c=1; if (c) //Do stuff here 

这将使您的代码大小减少25个字节;-)

演示 :另一个想法是在http://jsfiddle.net/h3qJB/ 。 请告诉我它是怎么回事。

你也可以做链接:

 $('#test1, #test2, #test3, #test4').each(function(){ //...use this.value here }); 

可能是De Morgan定律让您了解如何使逻辑更紧凑(虽然我不确定具体情况是什么, 或者它比评估值更简单)。

 var boolean1 = (($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value')) var boolean2 = (($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) if (boolean1 && boolean2) alert("bingo"); else alert("buzzinga");