我开始一个项目与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() { /* do something */ });
这将检查每一个元素,看它是否有一个“button”类。
相反,你可以帮助它,比如:
$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });
这是我去年从Rebecca Murphy的博客中学到的
更新:这个答案是2年前给出的,不适合当前版本的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);
解释
我对JavaScript也这么说,但是jQuery, JavaScript永远不应该取代CSS。
另外,确保站点对于关闭JavaScript的人来说是可用的(现在不像以前那么重要了,但拥有一个完全可用的站点总是好的)。
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#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");
});
当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。
编辑:在评论中加入建议。
避免多次搜索整个DOM。这确实会耽误你的剧本。
Bad:
$(".aclass").this();
$(".aclass").that();
...
好:
$(".aclass").this().that();
Bad:
$("#form .text").this();
$("#form .int").that();
$("#form .choice").method();
好:
$("#form")
.find(".text").this().end()
.find(".int").that().end()
.find(".choice").method();