我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
避免滥用文件准备。 保持文档仅为初始化代码准备。 始终在文档外部提取函数,以便它们可以被重用。
我在doc ready语句中看到了数百行代码。丑陋,不可读,不可能维护。
其他回答
过度使用链条。
看到这个:
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 );
事件
$("selector").html($("another-selector").html());
不会克隆任何事件-你必须重新绑定它们。
根据JP的评论- clone()如果您传递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.
})
});
避免多次搜索整个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();