我有一个小的 jQuery 代码来处理一些切换类和 HTML5 本地存储,我想将它转换成现代的 vanilla JS 代码。 我不得不说我不知道从哪里开始。
有人能告诉我现代 JS 代码的正确方法吗?我真的很感激。
示例演示: http://jsbin.com/wimojapowo/1/edit?html,css,js,output
$('#container').toggleClass(localStorage.toggled);
$('.bar-toggle').on('click', function() {
//localstorage values are always strings (no booleans)
if (localStorage.toggled != "with_toggle") {
$('#container').toggleClass("with_toggle", true);
localStorage.toggled = "with_toggle";
} else {
$('#container').toggleClass("with_toggle", false);
localStorage.toggled = "";
}
});
最佳答案
首先请注意,您的 jQuery 示例比它需要的更复杂。你可以这样做:
$('.bar-toggle').on('click', function() {
$('#container').toggleClass("with_toggle", localStorage.toggled != "with_toggle");
localStorage.toggled = localStorage.toggled == "with_toggle" ? '' : 'with_toggle';
});
要将其转换为纯 JS,您可以使用 classList.toggle()
方法:
document.querySelectorAll('.bar-toggle').forEach(function(el) {
el.addEventListener('click', function() {
this.classList.toggle("with_toggle", localStorage.toggled != "with_toggle");
localStorage.toggled = localStorage.toggled == "with_toggle" ? '' : 'with_toggle';
});
})
有关 classList
的更多信息,请访问 MDN
关于javascript - 如何将 jQuery ToggleClass 和 if/else 代码重写为 vanilla JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631340/