jQuery的行悬停和点击事件 [英] jquery row hover and click events

查看:157
本文介绍了jQuery的行悬停和点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示悬停行,这对我来说效果很好.同时,我想在单击时突出显示悬停的行.到目前为止,以下是我的代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆