Javascript 用于检查多个值的 jQuery 'if' 条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10597015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:03:50  来源:igfitidea点击:

A jQuery 'if' condition to check multiple values

javascriptjquery

提问by user1060990

In the code below, is there a better way to check the condition using jQuery?

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

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

回答by David M?rtensson

Unless there are other concerns, like if you will reuse the #test1, ... fields for more processing, yours should be good.

除非有其他问题,比如如果您将重用 #test1, ... 字段进行更多处理,您的应该很好。

If you will fetch any of the values again to do something I would recommend storing the $('#test1') result in a variable so that you do not need to requery the dom.

如果您将再次获取任何值来做某事,我建议将 $('#test1') 结果存储在一个变量中,这样您就不需要重新查询 dom。

Ex:

前任:

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');
}

This also improves readability of the row ;)

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

回答by David M?rtensson

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

This will decrease your code size by 25 bytes;-)

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

回答by The System Restart

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

回答by Tats_innit

Demo: just another idea is at http://jsfiddle.net/h3qJB/. Please let me know how it goes.

演示:另一个想法是在http://jsfiddle.net/h3qJB/。请告诉我进展如何。

You can also do chaining like:

您还可以进行链接,例如:

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

It might be that De Morgan's lawsgives you an idea of how to make the logic a bit more compact (although I am not sure what is the specific case oris it as simple as comparing values).

可能是德摩根定律让您了解如何使逻辑更加紧凑(尽管我不确定具体情况是什么,或者它是否像比较值一样简单)。

Code

代码

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