2011-05-27 191 views
5

有一个与jQuery的小混乱的问题,并选择/造型表中的列。jQuery的第n个孩子选择器

下面的代码工作:

$(function() { 
     $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child(10)").each(function() { 
      $(this).toggleClass("colhighlight"); 
     }); 
     }); 
    }); 

但这代码,改变第n个孩子(10)到第n个孩子(ICOL)产生错误 “未捕获的异常:语法错误,不能识别的表达式::第n孩子“

$(function() { 
     $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child(iCol)").each(function() { 
      $(this).toggleClass("colhighlight"); 
     }); 
     }); 
    }); 

任何帮助将不胜感激。

回答

14
 $("table tr td:nth-child(" + iCol + ")").each(function() { 
     $(this).toggleClass("colhighlight"); 
    }); 

第n个孩子预计一个整数,而不是字符串,所以你可以使用串联来解决问题。

+0

谢谢你,对于 “为什么” – chrisk 2011-05-27 10:34:32

+1

第n个孩子的答案和解释也接受一些关键字和等式。从下面的jQuery文档中查看: '每个匹配的孩子的索引,从1开始,字符串偶数或奇数,或者一个等式(例如:nth-​​child(偶数),:nth-​​child(4n) )' – Owen 2012-11-16 11:47:10

3

试试这个:

"table tr td:nth-child("+iCol+")" 
2

把它变成这样:

$(function() { 
    $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child(" + iCol + ")").each(function() { 
     $(this).toggleClass("colhighlight"); 
     }); 
    }); 
    }); 
0

试试这个:

$(function() { 
     $("table").delegate('th.selcol','click', function(e) { 
     var iCol = $(this).parent().children().index(this)+1; 
     $("table tr td:nth-child("+iCol+")").each(function() { 
      $(this).toggleClass("colhighlight"); 
     }); 
     }); 
    }); 

希望工程:)

+0

谢谢,那是有效的。 – chrisk 2011-05-27 10:29:37

+0

@ chrisk:很好,你会介意选择一个答案作为解决方案吗? – 2011-05-27 10:36:05