2012-02-14 26 views
2

我想將數組發送到eq函數作爲參數。這樣的:jquery數組轉換爲eq函數

$(this).find('tr').not(':eq(array)').each(function(){ 

}); 

我這樣做是使用一個循環,並eval功能,但它並不容易編輯。這是我的代碼。

$.fn.grilestir = function(options){ 

var nots = ''; 

for(var i=0;i<options.row_numbers.length;i++){ 
    nots += "not(':eq("+options.row_numbers[i]+")')."; 
} 

    eval("$(this).find('tr')."+nots+"each(function(){\ 
     var tr = $(this); var orj;\ 
     if(options.mod == 'passive-rows'){\ 
      $(this).mouseover(function(){\ 
       orj = tr.css('backgroundColor');\ 
       tr.css('backgroundColor', '#777777');\ 
      });\ 
      $(this).mouseout(function(){\ 
       tr.css('backgroundColor', orj); \ 
      });\ 
     }\ 
    });"); 

} 

有沒有辦法做到這一點?

+0

如果它的jQuery對象的數組,你可以做'。不是(陣列)'。你的數組包含什麼數據?另外,使用'eval()'不是一個好主意。 – Bojangles 2012-02-14 14:06:17

+0

ewww eval是邪惡的 – mcgrailm 2012-02-14 14:08:29

回答

4

我假設你的數組包含一組代表元素索引的數字。 eq選擇器將無法使用。

你可以使用filter減少匹配元素集合到那些在索引你的數組中:

var arr = [1, 2]; 
$("someSelector").filter(function(index) { 
    return arr.indexOf(index) > -1; 
}); 

這裏有一個working example

請注意使用Array.prototype.indexOf,這在舊版瀏覽器中不可用(值得注意的是IE <版本9)。但是,有很多墊片可以解決這個問題。 或者,在評論(感謝@mcgrailm)指出的那樣,你可以使用jQuery.inArray

var arr = [1, 2]; 
$("someSelector").filter(function(index) { 
    return $.inArray(index, arr) > -1; 
}); 
+0

+1非常好我知道有一個很好的方法來做到這一點,想不到它 – mcgrailm 2012-02-14 14:11:50

+0

jQuery的inArray()函數可以覆蓋舊版本嗎? – mcgrailm 2012-02-14 14:18:50

+0

@mcgrailm - 的確如此。我總是忘記那個有用的小東西! – 2012-02-14 14:20:27