繁体   English   中英

单击一行时,如何将“选定”类添加到表的一行?

[英]How can I add a “selected” class to just one row of a table when a row is clicked?

我使用以下代码:

$("#dataTable tbody").on("click", "tr", function (event) {
    if (!$(this).hasClass('row_selected')) {
        $(oTable.fnSettings().aoData).each(function () {
            $(this.nTr).removeClass('row_selected');
        });
        $(this).addClass('row_selected');
        gridClickHandler($(this));
    }
});

单击一行时,如果已选择该行,则不会发生任何操作。 如果没有,那么所有行都删除了类,并且当前行添加了row_selected类。

但是这很慢,因为我的表有很多行。 目前的延迟看起来不太好。 我想到的是将addClass移动到开头。 但是,如果我这样做,.each循环将删除它。

有没有办法让我的工作更有效率(更快的响应)?

<table id-"dataTable">
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
</table> 

这是一个样本

$('table').on('click', 'tr', function() {

    var row = $(this);                 //cache the row

    if(!row.hasClass('selected'){
        row.addClass('selected')       //add class to clicked row
            .siblings()                //get the other rows
            .removeClass('selected');  //remove their classes
        gridClickHandler(row);
    }
});​

使用.on()的优点是它只为子节点( tr )将一个事件处理程序绑定到父节点(在本例tabletable )。 在每一行上使用.click()意味着每个 tr元素都有一个处理程序,它是一个开销。

因此,例如,如果我有一千行,当你使用.click()时会有一千个点击处理程序,而不是只使用table上的处理程序来监听使用.on()时所有tr的点击事件。

$("#dataTable tbody tr").click(function () {
    $('#dataTable tbody tr.selected').removeClass('selected');
    $(this).addClass('selected');
    gridClickHandler($(this));
});

检查这个jsfiddle ,即使有大桌子也能很快工作!

- 评论后编辑 -

尝试这个:-

 $("#dataTable tbody tr").on("click", "tr", function (event) {        
         $("#dataTable tbody tr").removeClass('row_selected');
         $(this).addClass('row_selected');
     }
 });
$("#dataTable").on("click", "tr", function (e) {
    var $this = $(this);
    // this line removes all selected classes from the rows siblings
    $this.siblings().removeClass("row_selected");
    // this line will toggle the selected class,
    // therefore deselecting the row if it has been selected before
    $this.toggleClass("row_selected");
    gridClickHandler($this);
});

或者,缓存先前选择的行。

(function() {
    var $oldSelected = null;

    $("#dataTable").on("click", "tr", function (e) {
        var $this = $(this);
        // this line removes all selected classes from the rows siblings
        $oldSelected.removeClass("row_selected");
        // this line will toggle the selected class,
        // therefore deselecting the row if it has been selected before
        $oldSelected = $this.addClass("row_selected");
        gridClickHandler($this);
    });

})();

作为旁注,缓存jQuery调用 - 或者你需要反复进行的函数调用的结果 - 总是一个节省处理时间的好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM