我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
在一个小项目中使用jQuery,只需几行普通的JavaScript就可以完成。
其他回答
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#button').click(function() {
$('#label').method();
$('#label').method2();
$('#label').css('background-color', 'red');
});
而不是:
$('#button').click(function() {
var $label = $('#label');
$label.method();
$label.method2();
$label.css('background-color', 'red');
});
或者更好的链接:-
$('#button').click(function() {
$("#label").method().method2().css("background-color", "red");
});
当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。
编辑:在评论中加入建议。
避免多次搜索整个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();
尝试分离出匿名函数,这样就可以重用它们。
//Avoid
$('#div').click( function(){
//do something
});
//Do do
function divClickFn (){
//do something
}
$('#div').click( divClickFn );
事件
$("selector").html($("another-selector").html());
不会克隆任何事件-你必须重新绑定它们。
根据JP的评论- clone()如果您传递true,则会重新绑定事件。
避免创建多个相同的jQuery对象
//Avoid
function someFunc(){
$(this).fadeIn();
$(this).fadeIn();
}
//Cache the obj
function someFunc(){
var $this = $(this).fadeIn();
$this.fadeIn();
}