我开始一个项目与jQuery。

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


当前回答

如果你想让用户在他们的浏览器中看到html实体,使用'html'而不是'text'来注入Unicode字符串,例如:

$('p').html("Your Unicode string")

其他回答

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

像这样

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

将id而不是jQuery对象传递给函数:

myFunc = function(id) { // wrong!
    var selector = $("#" + id);
    selector.doStuff();
}

myFunc("someId");

传递一个包装集要灵活得多:

myFunc = function(elements) {
    elements.doStuff();
}

myFunc($("#someId")); // or myFunc($(".someClass")); etc.

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

跟“回购人”说的差不多,但不完全一样。

在开发ASP时。NET winforms,我经常这样做

$('<%= Label1.ClientID %>');

忘记#符号。正确的形式是

$('#<%= Label1.ClientID %>');

事件

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

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

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