我开始一个项目与jQuery。

在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?


当前回答

事件

$("selector").html($("another-selector").html());

不会克隆任何事件-你必须重新绑定它们。

根据JP的评论- clone()如果您传递true,则会重新绑定事件。

其他回答

使用ClientID在ASP中获取控件的“真实”id。网络项目。

jQuery('#<%=myLabel.ClientID%>');

另外,如果你在SharePoint内部使用jQuery,你必须调用jQuery. noconflict()。

过度使用链条。

看到这个:

this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

解释

避免多次搜索整个DOM。这确实会耽误你的剧本。

Bad:

$(".aclass").this();
$(".aclass").that();
...

好:

$(".aclass").this().that();

Bad:

$("#form .text").this();
$("#form .int").that();
$("#form .choice").method();

好:

$("#form")
    .find(".text").this().end()
    .find(".int").that().end()
    .find(".choice").method();

我对JavaScript也这么说,但是jQuery, JavaScript永远不应该取代CSS。

另外,确保站点对于关闭JavaScript的人来说是可用的(现在不像以前那么重要了,但拥有一个完全可用的站点总是好的)。

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

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

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

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

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

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

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