JavaScript Event Delegation without an actual event?
$(document).ready(function(){
//add background-color to all odd rows
//very important!!!
$("#tab3 tbody tr:odd").css("background-color", "#DCF1FD");
//change color on hover
//less important!!! 开发者_如何学C
$("#tab3 tbody tr").hover(
function () {
$(this).css("color", "red");
},
function () {
$(this).css("color", "#000");
}
);
});
Is there a way to make it work after I edit the table.
EDIT:This must work on IE8use jQuery delegate
on the table that will work even if you update the table rows dynamically because the event is attached to table and not each rows of it.
$(document).ready(function(){
$("#tab3 tbody tr:odd").css("background-color", "#DCF1FD");
$("#tab3").delegate('tbody tr', 'hover', function(){
$(this).css("color", "red");
},
function () {
$(this).css("color", "#000");
});
});
If you are updating the whole table dynamically then use this
$(document).delegate('#tab3 tbody tr', 'hover', function(){
$(this).css("color", "red");
},
function () {
$(this).css("color", "#000");
});
You can set the background color of odd row with simple css
#tab3 tbody tr:nth-child(odd)
{
background: #DCF1FD;
}
... Or you could just use CSS to define the backgrounds for even rows, odd rows and the hover state. Se the first answer to this question. (EDIT: fixed link, it was pointing the wrong SO thread).
精彩评论