7

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

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

4 回答 4

5

除非有其他问题,例如如果您将重用 #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');
}

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

于 2012-05-15T08:41:59.610 回答
1
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 个字节;-)

于 2012-05-15T08:45:39.663 回答
1

演示:另一个想法是在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");
于 2012-05-15T08:56:45.843 回答
1
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;
   }
});
于 2012-05-15T08:53:16.080 回答