我在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
});
我可以用全局做到这一点,但我想知道闭包是否会使我的代码变得更好;我知道闭包的概念,它允许函数记住它们的状态,但我不确定如何使它在这里工作。
感谢您的建议。
答案 0 :(得分:4)
Clsoures不适用于此,因为您有两个不相关的功能。
相反,您应该使用$(this).data(...)
,它存储与元素关联的任意数据。
答案 1 :(得分:1)
这里没有真正需要的闭包 - 你只需要在鼠标输入时将红色/蓝色类推入其他数据容器中,然后在鼠标离开时恢复它。
$('.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,这样黄色类只会覆盖蓝色/红色类的效果,减少明确删除后者的需要。