jQuery的行悬停和点击事件 [英] jquery row hover and click events
问题描述
我正在尝试突出显示悬停行,这对我来说效果很好.同时,我想在单击时突出显示悬停的行.到目前为止,以下是我的代码:
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');
});
如果我使click事件与上面相同,则它不起作用.
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?
推荐答案
更新:以下是使用CSS类的更好版本:
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', '');
});
CSS在哪里:
.simplehighlight {
background-color: #fff;
}
.clicked {
background-color: #ffdc87;
}
旧答案: 有效,但不必要的复杂性.
click
仅接受一个回调,而不接受两个.您可以使用data
来检查是否单击了行:
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');
}
});
然后为了不更改mouseleave
上的呼叫者,请检查clicked
值:
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');
}
});
这篇关于jQuery的行悬停和点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!