I am trying to highlight a row on hover which works fine for me. At the same time, I want to highlight the hovered row when it is clicked. Below is my code till now:
$(".simplehighlight").hover(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function开发者_高级运维() {
$(this).children().css('backgroundColor', '#fff');
});
If I make the click event same as above, its not working.
$(".simplehighlight").click(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function() {
$(this).children().css('backgroundColor', '#fff');
});
Any suggestions on how to achieve this?
Update: Here is a much better version using CSS classes:
$(".simplehighlight").click(function() {
$(this).toggleClass('clicked');
// comment the following line if you don't want to dehighlight other rows
$(this).siblings().removeClass('clicked');
});
$(".simplehighlight").hover(function() {
$(this).children().css('backgroundColor', '#ffdc87');
}, function() {
$(this).children().css('backgroundColor', '');
});
Where the CSS is:
.simplehighlight {
background-color: #fff;
}
.clicked {
background-color: #ffdc87;
}
DEMO
Old answer: Works but unnecessary complex.
click
only accepts one callback, not two. You could use data
to check whether row is clicked or not:
$(".simplehighlight").click(function() {
var clicked = $(this).data('clicked');
$(this).data('clicked', !clicked);
if(clicked) {
$(this).children().css('backgroundColor', '#fff');
}
else {
$(this).children().css('backgroundColor', '#ffdc87');
}
});
Then in order to not change the caller on mouseleave
, check the clicked
value:
$(".simplehighlight").hover(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function() {
if(!$(this).data('clicked')) {
$(this).children().css('backgroundColor', '#fff');
}
});
Working DEMO
If you want to de-highlight each row after clicking another, you could do something like this:
$('tr').click(function(){
$(this).children().css('backgroundColor', '#ffdc87');
$(this).siblings().children().css('backgroundColor', '#ffffff');
});
Demo
Using tbody:
$('tbody tr').click(function(){
$(this).children().css('backgroundColor', '#ffdc87');
$(this).siblings().children().css('backgroundColor', '#ffffff');
});
Demo
i don' think is this valid
$(".simplehighlight").click(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function() {
$(this).children().css('backgroundColor', '#fff');
});
change to
$(".simplehighlight").click(function() {
$(this).children().css('backgroundColor', '#ffdc87');
});
unlike .hover() .click() takes a single callback function .. see .toggle() instead... or you can use a css class to keep track of states - see these examples: http://www.elated.com/articles/jquery-manipulating-element-classes/
I would suggest this approach:
CSS:
.highlight { background-color: #ffdc87 }
JS:
$('tr').click(function(){
$('tr').children().removeClass('highlight')
$(this).children().addClass('highlight');
});
Demo: http://jsfiddle.net/W3sZS/1/
精彩评论