1

检查选项值是否等于多个值中的任何一个的最简单方法是什么?

这有效,但只允许检查一个值。

if ($(this).val() == 'QA') {
   //do something
} 

我想检查多个值。

if ($(this).val() == 'QA, Efficiency, Legal, Time, BadDebt, WriteOff, BusinessInterruption') {
   //do something
} 

我想我可以做到这一点,但似乎代码太多了?

if ($(this).val() == 'QA' || $(this).val() == 'Efficiency') {
   //do something
} 
4

1 回答 1

2

你可以使用$.inArray()

var valuesArray = ['QA', 'Efficiency', 'Legal', 'Time', 'BadDebt', 'WriteOff','BusinessInterruption'];

if ($.inArry($(this).val(),valuesArray) !== -1) {
    // value is present
}

或者,在支持的浏览器中Array.indexOf()

if (valuesArray.indexOf($(this).val()) !== -1) {
    // value is present
}

你也可以使用一个简单的开关:

switch($(this).val()) {
    case 'QA':
    case 'Efficiency':
    case 'Legal':
    case 'Time':
    case 'BadDebt':
    case 'WriteOff':
    case 'BusinessInterruption':
         /* switches continue with all subsequent comparisons until they reach
            a `break`, so this function 'doStuff()' will be executed if *any*
            of the above match */
        doStuff();
    break;
    default:
        noneOfTheAboveMatched();
        break;
}

参考:

于 2013-02-27T21:39:08.377 回答