live 函数内的 jquery 变量不起作用
我有这段代码,
$('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();
})
我尝试优化这段代码,将选择器存储在变量中。
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();
})
除了第三行之外,它都有效。 `$fonts_links.removeClass('选定'); 这太奇怪了..有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您说过“它可以工作,除了第三行。”但您没有说它如何不起作用。
但由于
live
的全部目的是动态处理 DOM 的更改,在这种情况下,您可能不想缓存选择器的结果:如果在缓存结果后添加更多列表项,它们将不会添加到您缓存的 jQuery 实例中,因此您当处理程序下次运行时,最终会丢失这些类(不会从中删除“选定的”类)。因此,如果这就是您所看到的...如果
wizard
元素是稳定的(不是动态的),您可以这样做:这样,您只缓存稳定位,并且您通过使用
delegate
明确告诉 jQuery 委托的根是什么(其中是live
的变体,植根于特定元素)。题外话:除非您在野外发现原始代码存在性能问题,否则缓存可能不是您的朋友——缓存是内存使用(和复杂性)与内存使用(和复杂性)之间的权衡执行速度,可能最好只在遇到实际问题时使用它。但我假设你这样做是有原因的,因此有上面的建议。
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
live
is 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
wizard
element 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 oflive
that'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.