2012-08-13 100 views
2

我相信可以將一個DOM對象數組傳遞給jQuery的選擇器,以便您可以同時處理多個對象。我試着這樣做如下,但不能讓它出於某種原因...將數組傳遞給jQuery Selector

$(Sel).animate({ 
     backgroundColor: "#FF0000" 
    }, 250, 'linear', function() { 

     $(this).animate({ 
      backgroundColor: "#FFFFFF" 
     }, 250, 'linear'); 

    }); 

它實際上是有可能做到這一點還是我找錯了樹?

我把this jsFiddle放在一起測試一下。其目的是爲預訂系統選擇半小時的插槽,因此我需要在下一行操作「this」和下面的單元格。

任何意見不勝感激。從小提琴

代碼:

function HighlightCells() { 

    $('table#Calendar tbody tr td:not(".TimeCell")').live('mouseenter', function() { 
     var Sel = new Array(); 
     Sel[1] = $(this); 

     // Count number of previous TDs. Resut is base 0 
     var NumIn = $(this).prevAll('td').length; 

     // Increment count to compensate for nth-child being base 1 
     NumIn++; 

     var NextRow = $(this).closest('tr').next('tr'); 

     Sel[2] = $(NextRow).children("td:nth-child(" + NumIn + ")"); 

     // Animate the cell background colour red to white 
     $(Sel).animate({ 
      backgroundColor: "#FF0000" 
     }, 250, 'linear', function() { 

      $(this).animate({ 
       backgroundColor: "#FFFFFF" 
      }, 250, 'linear'); 

     }); 


     $('table#Calendar tbody td').live('mouseleave', function() { 
      $(this).text(""); 
     }); 

    }); 

} 

HighlightCells(); 
+1

[根據文檔(http://api.jquery.com/jQuery/# jQuery1),它有可能:*「'jQuery(elementArray)':一個包含一組DOM元素的數組來包裝在一個jQuery對象中。」*什麼是'Sel'? *編輯:* nvm,沒有看小提琴。 – 2012-08-13 15:41:15

回答

1

你可以做到這一點

var Sel = new Array(); 
Sel[1] = this; 

Sel[2] = NextRow.children("td:nth-child(" + NumIn + ")")[0]; 
// retrieves the DOM element 
// Also no need to wrap NextRow with $() since it's already a jQuery object 

http://jsfiddle.net/wirey00/AX3C8/27/

2

您正在使用jQuery對象的數組。相反,您需要一個DOM對象數組。

var Sel = new Array(); 
     Sel[1] = this; 

Sel[2] = $(NextRow).children("td:nth-child(" + NumIn + ")").get(); 

雖然,它就不能成爲Sel[0] = thisSel[1] = ...

+0

難道你不是指'var Sel = new Array;'? – 2012-08-13 15:42:36

+0

是的,這是小提琴中的一個錯字。 – 2012-08-13 15:43:18

+1

@火箭你不是指'var Sel = [「爲什麼這是稀疏的」,this]':P – Esailija 2012-08-13 15:43:23

3

您正在從一個jQuery對象數組中創建一個jQuery對象。你不能這樣做,這是行不通的。

你需要要麼使Sel DOM元素(數組注:數組索引從零開始,所以Sel[1]實際上是第二個元素,而是構建陣列時,使用.push除非你真的需要使用實際的鍵):

var Sel = []; // this is preferred over `new Array()` 
Sel.push($(this).get(0)); // or Sel.push(this) 
// ... 
Sel.push($(NextRow).children("td:nth-child(" + NumIn + ")").get(0)); 

或做Sel一個jQuery對象開始,然後添加的元素進去。

var Sel = $(); 
Sel = Sel.add(this); 
// ... 
Sel = Sel.add($(NextRow).children("td:nth-child(" + NumIn + ")")); 
// ... 
Sel.animate({ // sel is already a jQuery object, so we don't need `$(Sel)`