简体   繁体   中英

javascript closure to remember initial state

I have a div in CSS that works like this: SomeDiv has another class, that's sometimes SomeRedDiv and other times SomeBlueDiv. When I mouseenter on SomeDiv, I want it to add the class SomeYellowDiv. But when I mouseleave, I want it each div to return to its initial state, either SomeRedDiv or SomeBlueDiv. This is what I have:

     <div class="SomeDiv SomeRedDiv"></div>
     <div class="SomeDiv SomeBlueDiv"></div>

    $('.SomeDiv').mouseenter(function () {

       // this makes all SomeDivs turn yellow
       $(this).removeClass().addClass('SomeDiv SomeYellowDiv');
    });

    $('.SomeDiv').mouseleave(function () {

       // here I want to use closure so that the function remembers
       // which class it initially was; SomeBlueDiv or SomeRedDiv
       $('this).removeClass().addClass('SomeDiv'); // add the initial color class
    });

I could do this with a global but I want to see if a closure would make my code better; I know the concept of closure that allows functions to remember their state but I'm not sure how to make it work here.

Thanks for your suggestions.

Clsoures don't apply here, since you have two unrelated functions.

Instead, you should use $(this).data(...) , which stores arbitrary data associated with an element.

There's no real need for closures here - you just need to push the red/blue class into some other data container on mouse enter, then reinstate it on mouse leave.

$('.SomeDiv').mouseenter(function () {
    //remember the current colour class...
    $(this).data('orig-colour', $(this).is('.SomeDivBlue') ? 'Blue' : 'Red'));
    //...and now remove it and add yellow
    $(this).removeClass('SomeDivRed SomeDivBlue').addClass('SomeYellowDiv');
});

$('.SomeDiv').mouseleave(function () {
    //remove yellow and reinstate the original colour class
    $(this).removeClass('SomeDivYellow').addClass('SomeDiv'+$(this).data('orig-colour'));
});

Note also I remove only the classes that need to be removed, as opposed to your code where you were removing all classes then re-adding as required.

You might also want to think about delegating the event if you have a lot of divs as this is more optimal performance wise. This isn't a big change;

$('.SomeDiv').mouseenter(...

becomes something like

$('body').on('mouseenter', '.SomeDiv', ...

Finally, I assume there is some programmatical reason as to why you physically need to remove a class. If the purpose is purely visual, at the risk of pointing out the obvious, you should craft your CSS so the yellow class merely overrides the effects of the blue/red class, alleviating the need to explicitly remove the latter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM