一个 jQuery 'if' 条件,用于检查多个值

A jQuery 'if' condition to check multiple values

本文关键字:检查 用于 条件 jQuery if 一个      更新时间:2023-09-26

在下面的代码中,有没有更好的方法来使用 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  });

可能是德摩根定律让你知道如何使逻辑更紧凑一些(尽管我不确定具体情况是什么,还是像比较值一样简单)。

法典

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");