jQuery 第 n 个子级选择器

标签 jquery jquery-selectors css-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");
         });
      });
   });

但是这段代码将 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");
         });
      });
   });

任何帮助将不胜感激。

最佳答案

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

nth-child 需要一个整数,而不是字符串,因此您可以使用串联来解决您的问题。

关于jQuery 第 n 个子级选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6150923/

相关文章:

javascript - 如何选择具有特定模式 id 的所有文本区域

javascript - jquery 选择器缺少元素

css - 为什么:nth-child(2) selector work on what I expect to be :first-child?

html - CSS Sprite 背景和选择器

javascript - 在所有屏幕宽度上应用第 n 个 child

jquery - 使用 django-autocomplete-light 自动完成

javascript - 如何在 Javascript 中将 CLOB 转换为字符串

javascript - Jquery 自动建议不会更新新选择

javascript - 按自定义属性按字母顺序排列选择菜单中的选项

jquery - 选择器应该有多具体?