A componentized solution (ie, which can be encapsulated) is possible using jQuery and css classes:
$("#mytable > tbody > tr").on("click", function (e) {
$(this).siblings().removeClass("ativo");
$(this).toggleClass("ativo");
});
CSS:
.ativo {
background-color: #00F;
color: white;
}
Selecting a specific table, and specific rows
The selector in the root table (i.e. #mytable
), allows you to place other tables on the page without affecting them. Just like using the >
operator to get to row. This makes it possible to compose the solution.
Why use siblings to remove the active class?
In addition, removing the ativo
class through siblings
, leaves the solution well encapsulated to the desired table. You could have subtables inside the table, and still work.
The tbody
in the middle is used to select only rows of the body, neither the footer nor the header.
EDIT
You can use a style user-select: none
so that quick clicks on the same line do not end up selecting text.
And also a cursor: pointer
to indicate that the user can click there.
EDIT
To get into the merits of performance, and keeping the code readable, I'll just say one thing ...
until someone overcomes you
$("#mytable > tbody > tr").on("click", function (e) {
var $this = $(this);
// bem... esse não é o lugar mais recomendável para armazenar o cache, ou é?
this.$siblings = this.$siblings || $this.siblings();
this.$siblings.removeClass("ativo");
$this.toggleClass("ativo");
});