在下面的代码中,有没有更好的使用jQuery检查条件的方法?
if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))发布于 2012-05-15 16:42:00
除非有其他顾虑,例如如果您要重用#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-15 16:45:40
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-15 16:53:16
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;
}
});https://stackoverflow.com/questions/10597015
复制相似问题