我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
过度使用链条。
看到这个:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
解释
其他回答
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#button').click(function() {
$('#label').method();
$('#label').method2();
$('#label').css('background-color', 'red');
});
而不是:
$('#button').click(function() {
var $label = $('#label');
$label.method();
$label.method2();
$label.css('background-color', 'red');
});
或者更好的链接:-
$('#button').click(function() {
$("#label").method().method2().css("background-color", "red");
});
当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。
编辑:在评论中加入建议。
过度使用链条。
看到这个:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
解释
不要滥用插件。
大多数情况下,您只需要库和用户界面。如果你保持简单,你的代码在长期运行中是可维护的。并不是所有插件都得到支持和维护,实际上大多数插件都不是。如果你可以使用核心元素模拟功能,我强烈推荐你这么做。
插件很容易插入到代码中,为您节省了一些时间,但是当您需要额外的东西时,修改它们是一个坏主意,因为您失去了可能的更新。您在开始时节省的时间将在稍后更改已弃用插件时浪费掉。
明智地选择您使用的插件。 除了库和用户界面,我经常使用$。Cookie, $。形式,美元。验证和thickbox。至于其余部分,我主要开发自己的插件。
理解如何使用上下文。通常,jQuery选择器会搜索整个文档:
// This will search whole doc for elements with class myClass
$('.myClass');
但是你可以通过在上下文中搜索来加快速度:
var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);
避免创建多个相同的jQuery对象
//Avoid
function someFunc(){
$(this).fadeIn();
$(this).fadeIn();
}
//Cache the obj
function someFunc(){
var $this = $(this).fadeIn();
$this.fadeIn();
}