我开始一个项目与jQuery。

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


当前回答

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

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

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

其他回答

过度使用链条。

看到这个:

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

解释

尝试分离出匿名函数,这样就可以重用它们。

//Avoid
$('#div').click( function(){
   //do something
});

//Do do
function divClickFn (){
   //do something    
}

$('#div').click( divClickFn );

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

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

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

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

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

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

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

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

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

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