简体   繁体   English

使用jQuery将DOM元素保存到变量中

[英]Save DOM element into a variable with Jquery

I have a side-menu-bar with some dropdown-lists. 我有一个带有一些下拉列表的侧面菜单栏。 When i click on a list's child element, the menu closes. 当我单击列表的子元素时,菜单关闭。 When i click again on the menu, i want that dropdown list to be expanded. 当我再次单击菜单时,我希望该下拉列表得到扩展。 In this way, i thought that it will be alright to save the DOM element into a global variable, and expand it on onClick menu event. 这样,我认为可以将DOM元素保存到全局变量中,并在onClick菜单事件上将其展开。

That list contains li and ul elements, to expand that, i'll add a .css class named "open". 该列表包含liul元素,为进行扩展,我将添加一个名为“ open”的.css类。

The menu items didn't have any id-s to identify them. 菜单项没有任何id-s来标识它们。

How can i do this? 我怎样才能做到这一点?

globally {var selectedItem =null}



   // If user click any menu link
    $('.menu-layer a').on('click', function () {
   //--> selectedItem = getClickedElement
   //... other code
 }


  //If user clicks the hamburger menu
    listenForMenuLayer: function () {
    $('.nav-menu').on('click', function () {
   //--> selectedClick.addClass('open')
    //animation and other stuff code
     }}

Thanks 谢谢

You can try something like this, not saving it as a global variable but just listening for the click event to fire like this, I'd also suggest adding at least on id on the parent of it all so it's easier to target. 您可以尝试这样,而不是将其保存为全局变量,而只是监听click事件,这样,我还建议您至少在所有父项上添加id,这样更易​​于定位。

$( "#menu" ).on( "click", function() {
    $( "#menu" ).addClass( "open" )
});

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

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