简体   繁体   English

Jquery 到纯 javascript

[英]Jquery to pure javascript

I am trying to make a toggle menu and found this example( https://codemyui.com/responsive-sidebar-menu/ ) on Codepen.我正在尝试制作一个切换菜单,并在 Codepen 上找到了这个示例( https://codemyui.com/responsive-sidebar-menu/ )。 I would like to make the Jquery code into pure Javascript, but apparently there's something wrong with what I've written..我想将 Jquery 代码变成纯 Javascript,但显然我写的东西有问题..

and this is what I've written(I made id for main and added Onclick function on the burger menu, that's the only 2 differences from the original):这就是我写的(我为 main 制作了 id 并在汉堡菜单上添加了 Onclick 功能,这是与原版仅有的两个不同之处):

    function toggle(){
        var main = document.getElementById("mymain");
        var button = document.querySelectorAll(".button");
        var sidebarItem = document.querySelectorAll(".sidebar-item");

        main.classList.toggle("move-to-left");
        button.classList.toggle("active");
        sidebarItem.classList.toggle("active");

        for(let i = 0; i < sidebarItem.length; i++){
            sidebarItem[i].classList.toggle("active");
        }
    }

first, querySelectorAll give you a nodelist, not a nodeelement, so if you want to use classList, you need to loop over your nodelist.首先,querySelectorAll 给你一个节点列表,而不是节点元素,所以如果你想使用 classList,你需要遍历你的节点列表。 Try this :尝试这个 :

var button = [...document.querySelectorAll(".button")]
button.map( el => el.classList.toggle("active") )

i'm spreading the nodelist into an array, then i can use the map method我将节点列表传播到一个数组中,然后我可以使用 map 方法

apply this on all your querySelectorAll elements将此应用于所有 querySelectorAll 元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM