I am using the following code:
$("#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));
}
});
When a row is clicked then if the row is already selected nothing happens. If not then all the rows have the class removed and the current row has the row_selected class added.
However this is slow as my tables have many rows. It does not look good with the current delay. What I thought of was moving the addClass to the start. But if I do that the the .each loop removes it.
Is there a way I could make this work more efficiently (faster response)?
<table id-"dataTable">
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
Here’s a sample
The advantage of using
.on()is that it binds only one event handler to the parent (in this case,table) for the children (thetr). Using.click()on each row means there is one handler for eachtrelement which is an overhead.So for example, if I had a thousand rows, there would be a thousand click handlers when you use
.click()as opposed to only click handler on thetableto listen for all thetr‘s click events when using.on().