【问题标题】:The variable in element nth-child using jquery使用jquery的元素nth-child中的变量
【发布时间】:2015-09-14 04:46:31
【问题描述】:

我被卡住了,我无法使用变量和 jquery 溢出计数孩子。我做什么:

<ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
</ul>

<table>
  <tr>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

我想从列表中单击一个特定的孩子,并且在表格的同一行中更改了班级。

类似:

$('ul li:nth-child(' + count + ')').click(function() {
    $('table tr:nth-child(' + count + ')').addClass('active');
});

但我不知道如何正确使用变量'count'。

【问题讨论】:

    标签: jquery variables count jquery-selectors


    【解决方案1】:

    您可以使用$.fn.index 获取 LI 的当前索引并使用它来突出显示当前表行:

    $('ul li').click(function() {
        $('table tr:eq(' + $(this).index() + ')').addClass('active');
    });
    

    使用nth-child,您需要添加+1:'table tr:nth-child(' + ($(this).index() + 1) + ')'

    【讨论】:

      【解决方案2】:

      点击 li 先移除活动类并添加类,然后点击动态

      $('ul li').click(function() {
          $('.active').removeClass('active');
          $('table tr:eq(' + $(this).index() + ')').addClass('active');
      });
      

      Demo

      【讨论】:

        猜你喜欢
        • 2013-07-24
        • 2012-07-31
        • 1970-01-01
        • 1970-01-01
        • 2014-06-07
        • 2012-09-23
        • 1970-01-01
        • 2018-01-12
        相关资源
        最近更新 更多