I need to keep the color of the clicked div until another div of the same class gets clicked. Right now I have this code:

$('.aaa').mouseenter(function () {
    $(this).css('background', '#dddddd');
});
$('.aaa').mouseleave(function () {
    $(this).css('background', '#888888');
});
$('.aaa').click(function () {
    $(this).css('background', '#555555');
    $('.aaa').not(this).css('background', '#111111');
    $(this).off('mouseenter mouseleave');
    $('.aaa').not(this).on('mouseenter mouseleave');
});

http://jsfiddle.net/5jUP7/

Only problem here is that I can't re-enable previously disabled events (for previously clicked elements).

How can this be achieved?

有帮助吗?

解决方案

Put your handlers in functions, to make it easy to refer to them in multiple places.

$(".aaa").on({
    mouseenter: mouseEnter,
    mouseleave: mouseLeave
});

function mouseEnter() {
    $(this).css('background', '#dddddd');
}
function mouseLeave() {
    $(this).css('background', '#888888');
}
$(".aaa").click(function() {
    $(this).css('background', '#555555');
    $(".aaa").not(this).css('background', '#111111');
    $(this).off('mouseenter mouseleave');
    $(".aaa").not(this).on({
        mouseenter: mouseEnter,
        mouseleave: mouseLeave
    });
});

FIDDLE

其他提示

Have a look at this fiddle

You can do most of your work using simple CSS

HTML

<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>

CSS

.aaa {
    display:block;
    background:#888;
    width: 300px;
    height: 30px;
    border: 1px solid #000;
}
.aaa:hover,
.aaa.disabled:hover{
    display:block;
    background:#ddd;
}
.aaa.active {
    background:#111;
}
.aaa.disabled {
    background:#555;
}

JAVASCRIPT

$('.aaa').click(function () {
    $('.aaa').removeClass('active disabled');
    $(this).addClass('active');
    $('.aaa').not($(this)).addClass('disabled');
});

Don't disable anything. Just keep track of the previously clicked element.

var lastObjClicked;
function clicked(this){
  var thisClass = this.className;

  if( lastObjClicked.className == thisClass){
    document.getElementById(lastObjClicked.id).style.color = '#FF0000';
    document.getElementById(this.id).style.color = '#FF0000';

  }else{
    lastObjClicked = this;
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top