【问题标题】:How to select just a row of table using jQuery如何使用jQuery只选择一行表格
【发布时间】:2011-02-13 16:34:11
【问题描述】:

我在我的应用程序上创建了一个表,代码相同

<table class="spreadsheet">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</table>

我使用以下 jQuery 代码通过单击选择一行

 $("tr").click(function(){
 $(this).toggleClass("otherstyle");
}

我的css是

tr.otherstyle td
{
    background-color: #d1db3e;
    color:#000;
}

我希望当我点击一行时,其他行未选中, 并且只选择一行。

我们如何创建它?

【问题讨论】:

    标签: jquery html css html-table


    【解决方案1】:
    $("tr").click(function(){
    
     $('tr').removeClass("otherstyle");
     $(this).toggleClass("otherstyle");
    
    }
    

    $("tr").click(function(){     
    
     $(this).toggleClass("otherstyle").siblings().removeClass("otherstyle");
    
    }
    

    【讨论】:

      【解决方案2】:
      $("table.spreadsheet tr").click(function(){
          $("table.spreadsheet tr").removeClass("otherstyle");
          $(this).toggleClass("otherstyle");
      });
      

      查看working demo

      【讨论】:

        【解决方案3】:

        出于性能考虑,我会将 rahul 的答案更改为

        $("table.spreadsheet tr").click(function(){
            $("table.spreadsheet tr").removeClass("otherstyle");
            $(this).addClass("otherstyle"); // avoid checking if it has the class "otherstyle"
                                              // because it does not
        });
        

        这不是一个真正的杀戮,但是,嘿,我们不应该总是编写快速/优化的代码吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-30
          • 2014-05-28
          • 1970-01-01
          • 2012-01-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多