我开始一个项目与jQuery。

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


当前回答

不要使用裸类选择器,像这样:

$('.button').click(function() { /* do something */ });

这将检查每一个元素,看它是否有一个“button”类。

相反,你可以帮助它,比如:

$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });

这是我去年从Rebecca Murphy的博客中学到的

更新:这个答案是2年前给出的,不适合当前版本的jQuery。 其中一个评论包括一个测试来证明这一点。 还有一个更新的测试版本,其中包含了回答这个问题时的jQuery版本。

其他回答

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

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

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

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

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

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

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

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

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

在一个小项目中使用jQuery,只需几行普通的JavaScript就可以完成。

过度使用链条。

看到这个:

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

解释

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

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

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