javascript关闭以记住初始状态

javascript closure to remember initial state

本文关键字:初始状态 javascript      更新时间:2023-09-26

我在CSS中有一个div,它的工作原理是这样的:SomeDiv有另一个类,有时是SomeRedDiv,有时则是SomeBlueDiv。当我在SomeDiv上鼠标输入时,我希望它添加类SomeYellowDiv。但当我离开鼠标时,我希望它的每个div都返回到它的初始状态,SomeRedDiv或SomeBlueDiv。这就是我所拥有的:

     <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
    });

我可以用一个global来做这件事,但我想看看闭包是否会让我的代码变得更好;我知道闭包的概念,它允许函数记住它们的状态,但我不确定如何使它在这里工作。

谢谢你的建议。

Clsoures在这里不适用,因为您有两个不相关的函数。

相反,您应该使用$(this).data(...),它存储与元素关联的任意数据。

这里实际上不需要闭包——只需要在鼠标输入时将红/蓝类推入其他数据容器,然后在鼠标离开时将其恢复。

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

另外请注意,我只删除需要删除的类,而不是您的代码中删除所有类,然后根据需要重新添加。

如果您有很多div,您可能还想考虑委派事件,因为这更符合最佳性能。这不是什么大的变化;

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

变成类似的东西

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

最后,我认为有一些程序上的原因,为什么你需要删除一个类。如果目的纯粹是视觉的,冒着指出显而易见的风险,你应该设计你的CSS,这样黄色类只会覆盖蓝色/红色类的效果,从而减少明确删除后者的需要。