假设我有一个具有多个类的元素:<div id='foo' class='Test1 Test2 Test3'>foo</div>
以及在每个 keyup 事件上执行的脚本:
$('#foo').on('keyup', function() {
// Do something here that changes the classes
});
如何在初始 keyup 之前捕获该元素的初始类(并且仅在第一次初始更改),将它们存储在变量中,然后将它们重新应用到该元素?
我考虑过使用全局静态变量,但我相信有更好的解决方案。
最佳答案
如果数据属性未初始化,则将元素的类保存到该属性。
否则,从该数据属性恢复元素的类:
$('#foo').on('keyup', function() {
if(!$(this).data('classes')) {
$(this).data('classes', $(this).attr('class')); //store initial state
} else {
$(this).attr('class', $(this).data('classes')); //restore initial state
}
});
关于javascript - jQuery 将元素的类保存在静态变量中并重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279370/