我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
如果你多次bind()同一个事件,它将多次触发。为了安全起见,我通常总是unbind('click').bind('click')
其他回答
总是缓存$(this)到一个有意义的变量 特别是在.each()中
像这样
$(selector).each(function () {
var eachOf_X_loop = $(this);
})
误解在正确的上下文中使用此标识符。例如:
$( "#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.
})
});
过度使用链条。
看到这个:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
解释
不要滥用插件。
大多数情况下,您只需要库和用户界面。如果你保持简单,你的代码在长期运行中是可维护的。并不是所有插件都得到支持和维护,实际上大多数插件都不是。如果你可以使用核心元素模拟功能,我强烈推荐你这么做。
插件很容易插入到代码中,为您节省了一些时间,但是当您需要额外的东西时,修改它们是一个坏主意,因为您失去了可能的更新。您在开始时节省的时间将在稍后更改已弃用插件时浪费掉。
明智地选择您使用的插件。 除了库和用户界面,我经常使用$。Cookie, $。形式,美元。验证和thickbox。至于其余部分,我主要开发自己的插件。
理解如何使用上下文。通常,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);