我开始一个项目与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);

其他回答

不理解事件绑定。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和类。

理解如何使用上下文。通常,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);

不要使用裸类选择器,像这样:

$('.button').click(function() { /* do something */ });

这将检查每一个元素,看它是否有一个“button”类。

相反,你可以帮助它,比如:

$('span.button').click(function() { /* do something */ });
$('#userform .button').click(function() { /* do something */ });

这是我去年从Rebecca Murphy的博客中学到的

更新:这个答案是2年前给出的,不适合当前版本的jQuery。 其中一个评论包括一个测试来证明这一点。 还有一个更新的测试版本,其中包含了回答这个问题时的jQuery版本。

我的意见)

通常,使用jquery意味着你不必一直担心DOM元素。你可以这样写- $('div.mine'). addclass ('someClass')。Bind ('click', function(){alert('lalala')}) -这段代码将执行而不会抛出任何错误。

在某些情况下,这是有用的,在某些情况下-根本不是,但这是一个事实,jquery倾向于,嗯,空匹配友好。但是,如果试图将replaceWith与不属于文档的元素一起使用,则会抛出错误。我觉得这是违反直觉的。

另一个陷阱是,在我看来,由prevAll()方法返回的节点顺序- $('<div><span class="A"/><span class="B"/><span class="C"/><span class="D"/></div>').find('span:last-child').prevAll()。其实没什么大不了的,但我们应该记住这个事实。

避免创建多个相同的jQuery对象

//Avoid
function someFunc(){
   $(this).fadeIn();
   $(this).fadeIn();
}

//Cache the obj
function someFunc(){
   var $this = $(this).fadeIn();
   $this.fadeIn();
}