我正在和jQuery一起开始一个项目。
您在jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
发布于 2009-08-04 19:07:43
没有意识到性能影响,过度使用选择器,而不是将它们赋给局部变量。例如:
$('#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");
});
当我意识到调用堆栈是如何工作的时,我发现this是一个启发性的时刻。
编辑:将建议合并到评论中。
发布于 2009-08-04 19:21:22
了解如何使用上下文。通常,jQuery选择器将搜索整个文档:
// This will search whole doc for elements with class myClass
$('.myClass');
但你可以通过在上下文中搜索来加快速度:
var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);
发布于 2009-08-04 18:59:31
尝试拆分匿名函数,以便可以重用它们。
//Avoid
$('#div').click( function(){
//do something
});
//Do do
function divClickFn (){
//do something
}
$('#div').click( divClickFn );
https://stackoverflow.com/questions/1229259
复制相似问题