I have this piece of code
$('ul.fonts li', '#wizard').live('click', function(e){
$('ul.fonts li', '#wizard').removeClass('selected');
$(this).addClass('selected');
$('blockquote').css('font-family', $(this).find('a').attr("class") )
e.preventDefault();
})
I tried ti optimize this code storing the selector in a variable.
var $fonts_links = $('ul.fonts li', '#wizard')
$fonts_links.live('click', function(e){
$fonts_links.removeClass('selected');
$(this).addClass('selected');
$('blockquote').css('font-family', $(this).find('a').attr("class") )
e.preventDefault();
})
It works, except from the third line. `$fonts_links.removeClass(‘selected’);
This is so weird..some advice?
You’ve said “It works, except [for] the third line.” but you haven’t said how it doesn’t work.
But since the whole point of
liveis to handle your changing the DOM dynamically, you probably don’t want to cache the result of the selector in this situation: If you add more list items after you’ve cached the result, they won’t be added to the jQuery instance you’ve cached, and so you’ll end up missing those ones out (not removing the “selected” class from them) when the handler next runs. So if that’s what you’re seeing…If the
wizardelement is stable (not dynamic), you could do this:That way, you’re only caching the stable bit, and you’re explicitly telling jQuery what the root of the delegation is by using
delegate(which is a variant oflivethat’s rooted in a specific element).Off-topic: Unless you’re seeing a performance problem with the original code in the wild, caching may not be your friend anyway — caching is a trade-off between memory use (and complexity) vs. speed-of-execution, probably best to only use it when faced with a tangible problem. But I’m assuming you’re doing this for a reason, hence the suggestion above.