jquery行hover并单击事件

我试图突出显示hover行,这对我来说很好。 同时,我想在点击时突出显示hover的行。 以下是我的代码:

$(".simplehighlight").hover(function() { $(this).children().css('backgroundColor', '#ffdc87'); }, function() { $(this).children().css('backgroundColor', '#fff'); }); 

如果我将click事件与上面相同,则它不起作用。

  $(".simplehighlight").click(function() { $(this).children().css('backgroundColor', '#ffdc87'); }, function() { $(this).children().css('backgroundColor', '#fff'); }); 

有关如何实现这一目标的任何建议?

更新:这是一个使用CSS类的更好的版本:

 $(".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', ''); }); 

CSS的位置是:

 .simplehighlight { background-color: #fff; } .clicked { background-color: #ffdc87; } 

DEMO


老答案: 工作但不必要的复杂。

click只接受一个回调,而不是两个回调。 您可以使用data来检查是否单击了行:

 $(".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'); } }); 

然后,为了不在 mouseleave上更改调用者,请检查clicked值:

 $(".simplehighlight").hover(function() { $(this).children().css('backgroundColor', '#ffdc87'); }, function() { if(!$(this).data('clicked')) { $(this).children().css('backgroundColor', '#fff'); } }); 

工作演示

如果要在单击另一行后取消突出显示每一行,您可以执行以下操作:

 $('tr').click(function(){ $(this).children().css('backgroundColor', '#ffdc87'); $(this).siblings().children().css('backgroundColor', '#ffffff'); }); 

演示


使用tbody:

 $('tbody tr').click(function(){ $(this).children().css('backgroundColor', '#ffdc87'); $(this).siblings().children().css('backgroundColor', '#ffffff'); }); 

演示

我认为这是有效的

 $(".simplehighlight").click(function() { $(this).children().css('backgroundColor', '#ffdc87'); }, function() { $(this).children().css('backgroundColor', '#fff'); }); 

改成

 $(".simplehighlight").click(function() { $(this).children().css('backgroundColor', '#ffdc87'); }); 

与.hover()不同.click()采用单个回调函数..请参阅.toggle()而不是…或者您可以使用css类来跟踪状态 – 请参阅以下示例: http://www.elated。 COM /用品/ jQuery的操纵元素类/

我会建议这种方法:

CSS:

 .highlight { background-color: #ffdc87 } 

JS:

 $('tr').click(function(){ $('tr').children().removeClass('highlight') $(this).children().addClass('highlight'); }); 

演示: http : //jsfiddle.net/W3sZS/1/