简体   繁体   中英

How to select and highlight a single cell in HTML Table

I want to select a cell in a HTML table when clicking on it. Currently I use this:

$("td").click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
});​

an my css is:

td:hover, td.selected {
   background-color: #FF9900
}
td {padding: 5px;}

Hovering works just fine, but when I click on a cell it won't stay select.

How can I fix it

EDIT

You're right I shoud have give you more background info. I have to do a JavaFx programm for University. But JavaFX doesn't provide a table I wanted. So I decided get a WebView I this part of the application and make the table via a StringBuilder. In the following you see my current output (in the header is normaly the css and script link deleted it for this): https://jsfiddle.net/5c861zrg/

So in this condition it won't work-

I was able to get your code working however it would not unselect multiple cells of the same column. So I just modified it to this. Give it a try. Leave your CSS the same.

$("td").click(function(){
    $("td.selected").removeClass("selected");
    $(this).addClass("selected");
});

Your problem is you have one more row siblings() is not working for another row try do this

$("td").click(function() {
  $(".selected").parent().find('td').removeClass("selected");
  $(this).addClass("selected").siblings().removeClass("selected");
});

First you should find .selected class and you go to parent class and then you reach parent's td finally remove that you wanted class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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