我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
避免创建多个相同的jQuery对象
//Avoid
function someFunc(){
$(this).fadeIn();
$(this).fadeIn();
}
//Cache the obj
function someFunc(){
var $this = $(this).fadeIn();
$this.fadeIn();
}
其他回答
过度使用链条。
看到这个:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
解释
当使用$。ajax函数对服务器的ajax请求,你应该避免使用完整的事件来处理响应数据。无论请求是否成功,它都会触发。
用成功代替完成。
请参阅文档中的Ajax事件。
不要使用裸类选择器,像这样:
$('.button').click(function() { /* do something */ });
这将检查每一个元素,看它是否有一个“button”类。
相反,你可以帮助它,比如:
$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });
这是我去年从Rebecca Murphy的博客中学到的
更新:这个答案是2年前给出的,不适合当前版本的jQuery。 其中一个评论包括一个测试来证明这一点。 还有一个更新的测试版本,其中包含了回答这个问题时的jQuery版本。
误解在正确的上下文中使用此标识符。例如:
$( "#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.
})
});
不理解事件绑定。JavaScript和jQuery的工作方式不同。
根据大众需求,一个例子:
jQuery:
$("#someLink").click(function(){//do something});
没有jQuery:
<a id="someLink" href="page.html" onClick="SomeClickFunction(this)">Link</a>
<script type="text/javascript">
SomeClickFunction(item){
//do something
}
</script>
基本上JavaScript所需要的钩子不再是必要的。例如,使用内联标记(onClick等),因为您可以简单地使用开发人员通常用于CSS目的的ID和类。