我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
尝试分离出匿名函数,这样就可以重用它们。
//Avoid
$('#div').click( function(){
//do something
});
//Do do
function divClickFn (){
//do something
}
$('#div').click( divClickFn );
其他回答
如果你想让用户在他们的浏览器中看到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);
解释
当使用$。ajax函数对服务器的ajax请求,你应该避免使用完整的事件来处理响应数据。无论请求是否成功,它都会触发。
用成功代替完成。
请参阅文档中的Ajax事件。
在一个小项目中使用jQuery,只需几行普通的JavaScript就可以完成。
误解在正确的上下文中使用此标识符。例如:
$( "#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.
})
});