2012-08-13 44 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)`