简体   繁体   中英

Color table row if button clicked

I am looking to turn the whole row red in my table when clicked using javascript.

I have managed to turn single cells red with the below code but not the whole tr. Also once the row is red im unable to turn it back to white.

var ie = document.all
var ns = document.getElementById && !ie
function rowclick(e) {
var obj = ns ? e.target : event.srcElement
if (obj.tagName=="TD") {
obj.style.background="red"
obj.onblur=function() {
obj.style.background="white"
}
}
} 

Note that changing if (obj.tagName=="TD") { to if (obj.tagName=="TR") { does not work

 function rowclick(e) { var obj = this if (obj.tagName == "TR") { if (obj.style.backgroundColor === "red") obj.style.backgroundColor = "white" else obj.style.backgroundColor = "red" } } $('table tr').click(rowclick) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <table> <tr><td>hello</td><td>world</td></tr> <tr><td>hello</td><td>world</td></tr> <tr><td>hello</td><td>world</td></tr> </table> </div> 

Updated to toggle background color.

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