简体   繁体   中英

jQuery loses reference to cached element once class is removed

In my code example the subnav variable is supposed to cache a reference to ul.nav-categories DOM object, but it gets lost after the class is removed.

<ul class="nav-categories">
    <li>item 1</li>
    <li>item 2</li>
</ul>

jQuery

$subnav = $('ul.nav-categories');

if (*some condition*) {
    $subnav.removeClass('nav-categories');
} else {
    $subnav.addClass('nav-categories'); 
   /* ^^^^ at this point $subnav becomes undefined in jQuery addClass function, 
   shouldn't it save a reference to the object and not 'ul.nav-categories'??? 
   Am I caching ul reference incorrectly? */
}

$subnav can not become undefined in the specified code. But I suppose your fragment of js code is wrapped in some kind of function, and is called more than once.

Probably, it's called 1st time and removes class nav-categories .

Then it's called 2nd time, and attempts to get $('ul.nav-categories');

But that element already dont have class nav-categories .

So $subnav becomes undefined , because jQuery can't find node to set it.

try this :

<ul class="nav-categories flag">
    <li>item 1</li>
    <li>item 2</li>
</ul>

$subnav = $('ul.flag');

if (*some condition*) {
    $subnav.removeClass('nav-categories');
} else {
    $subnav.addClass('nav-categories'); 
}

The only condition is : don't remove the class "flag" or u can just use only $subnav = $("ul")

Why : if you are evaluating that condition many times, the first time JQuery will find the object and will remove the class, but all the other times the object $("ul.nav-categories") will not exist anymore.

Hope this help you ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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