2017-10-08 19 views
1

我有一個小的jQuery代碼來處理一些切換類和HTML5本地存儲,我想將它轉換成一個現代的香草JS代碼。 我不得不說我不知道​​從哪裏開始。如何將jQuery的ToggleClass和if/else代碼重寫爲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 = ""; 
    } 
}); 

回答

3

首先注意你的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'; 
    }); 
}) 
MDN

classList

更多信息