簡體   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