我开始一个项目与jQuery。

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


当前回答

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

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

myFunc("someId");

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

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

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

其他回答

过度使用链条。

看到这个:

this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

解释

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

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

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

缺陷:使用循环而不是选择器。

如果你发现自己在寻找jQuery '。每个方法迭代DOM元素,问问自己是否可以使用选择器来获取元素。

关于jQuery选择器的更多信息: http://docs.jquery.com/Selectors

缺点:没有使用Firebug这样的工具

Firebug实际上就是为这种调试而设计的。如果您打算在DOM中使用Javascript,则需要像Firebug这样的好工具来提供可见性。

有关Firebug的更多信息: http://getfirebug.com/

其他很棒的想法都在这一期的多态播客中: (jQuery秘密与戴夫沃德) http://polymorphicpodcast.com/shows/jquery/

避免滥用文件准备。 保持文档仅为初始化代码准备。 始终在文档外部提取函数,以便它们可以被重用。

我在doc ready语句中看到了数百行代码。丑陋,不可读,不可能维护。