A jQuery 'if' condition to check multiple values

后端 未结 4 1552
长发绾君心
长发绾君心 2021-01-18 14:55

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

if(($(\'#test1\').val() == \'first_value\')||($(\'#test2\').val() == \'second_v         


        
4条回答
  •  长情又很酷
    2021-01-18 15:17

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

    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.

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

提交回复
热议问题