jQuery nth-child选择器

chr*_*isk 6 jquery css-selectors jquery-selectors

在jQuery中遇到一个小问题,并在表中选择/样式化列.

以下代码有效:

   $(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");
         });
      });
   });
Run Code Online (Sandbox Code Playgroud)

但是这段代码,将nth-child(10)更改为nth-child(iCol)会产生错误"未捕获的异常:语法错误,无法识别的表达式:: nth-child"

   $(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");
         });
      });
   });
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Ber*_*rak 15

     $("table tr td:nth-child(" + iCol + ")").each(function () {
        $(this).toggleClass("colhighlight");
     });
Run Code Online (Sandbox Code Playgroud)

nth-child需要一个整数,而不是一个字符串,所以你可以使用连接来解决你的问题.