我开始一个项目与jQuery。

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


当前回答

过度使用链条。

看到这个:

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

解释

其他回答

误解在正确的上下文中使用此标识符。例如:

$( "#first_element").click( function( event)
{
   $(this).method( ); //referring to first_element
   $(".listOfElements").each( function()
   {
      $(this).someMethod( ); // here 'this' is not referring first_element anymore.
   })
});

这里有一个解决方法的例子:

$( "#first_element").click( function( event)
{
   $(this).method( ); //referring to first_element
   var $that = this;
   $(".listOfElements").each( function()
   {
      $that.someMethod( ); // here 'that' is referring to first_element still.
   })
});

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

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

过度使用链条。

看到这个:

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

解释

避免多次搜索整个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();

如果您计划在大量数据中使用Ajax,比如一个有20列的1500行表,那么甚至不要考虑使用jQuery将这些数据插入到HTML中。使用纯JavaScript。jQuery在较慢的机器上太慢了。

而且,有一半的时间jQuery会做一些导致它变慢的事情,比如试图解析传入HTML中的脚本标记,以及处理浏览器的异常。如果您想要更快的插入速度,请坚持使用纯JavaScript。