我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
理解如何使用上下文。通常,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);
其他回答
误解在正确的上下文中使用此标识符。例如:
$( "#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.
})
});
在一个小项目中使用jQuery,只需几行普通的JavaScript就可以完成。
使用ClientID在ASP中获取控件的“真实”id。网络项目。
jQuery('#<%=myLabel.ClientID%>');
另外,如果你在SharePoint内部使用jQuery,你必须调用jQuery. noconflict()。
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#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");
});
当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。
编辑:在评论中加入建议。
使用字符串累加器样式
使用+运算符在内存中创建一个新的字符串,并将连接的值赋给它。只有在此之后,结果才被赋值给一个变量。 为了避免连接结果的中间变量,可以使用+=运算符直接分配结果。 慢:
a += 'x' + 'y';
速度:
a += 'x';
a += 'y';
基元操作可能比函数调用快
考虑在性能关键循环和函数中使用替代基元操作而不是函数调用。 慢:
var min = Math.min(a, b);
arr.push(val);
速度:
var min = a < b ? a : b;
arr[arr.length] = val;
请参阅JavaScript性能最佳实践