我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
避免滥用文件准备。 保持文档仅为初始化代码准备。 始终在文档外部提取函数,以便它们可以被重用。
我在doc ready语句中看到了数百行代码。丑陋,不可读,不可能维护。
其他回答
避免创建多个相同的jQuery对象
//Avoid
function someFunc(){
$(this).fadeIn();
$(this).fadeIn();
}
//Cache the obj
function someFunc(){
var $this = $(this).fadeIn();
$this.fadeIn();
}
误解在正确的上下文中使用此标识符。例如:
$( "#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选择器会搜索整个文档:
// 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);
使用ClientID在ASP中获取控件的“真实”id。网络项目。
jQuery('#<%=myLabel.ClientID%>');
另外,如果你在SharePoint内部使用jQuery,你必须调用jQuery. noconflict()。
如果您计划在大量数据中使用Ajax,比如一个有20列的1500行表,那么甚至不要考虑使用jQuery将这些数据插入到HTML中。使用纯JavaScript。jQuery在较慢的机器上太慢了。
而且,有一半的时间jQuery会做一些导致它变慢的事情,比如试图解析传入HTML中的脚本标记,以及处理浏览器的异常。如果您想要更快的插入速度,请坚持使用纯JavaScript。