我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#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");
});
当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。
编辑:在评论中加入建议。
其他回答
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#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();
跟“回购人”说的差不多,但不完全一样。
在开发ASP时。NET winforms,我经常这样做
$('<%= Label1.ClientID %>');
忘记#符号。正确的形式是
$('#<%= Label1.ClientID %>');
理解如何使用上下文。通常,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);
总是缓存$(this)到一个有意义的变量 特别是在.each()中
像这样
$(selector).each(function () {
var eachOf_X_loop = $(this);
})