我开始一个项目与jQuery。

在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?


当前回答

总是缓存$(this)到一个有意义的变量 特别是在.each()中

像这样

$(selector).each(function () {
    var eachOf_X_loop = $(this); 
})

其他回答

避免创建多个相同的jQuery对象

//Avoid
function someFunc(){
   $(this).fadeIn();
   $(this).fadeIn();
}

//Cache the obj
function someFunc(){
   var $this = $(this).fadeIn();
   $this.fadeIn();
}

没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-

$('#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"); 
});

当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。

编辑:在评论中加入建议。

我对JavaScript也这么说,但是jQuery, JavaScript永远不应该取代CSS。

另外,确保站点对于关闭JavaScript的人来说是可用的(现在不像以前那么重要了,但拥有一个完全可用的站点总是好的)。

理解如何使用上下文。通常,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);

事件

$("selector").html($("another-selector").html());

不会克隆任何事件-你必须重新绑定它们。

根据JP的评论- clone()如果您传递true,则会重新绑定事件。