我开始一个项目与jQuery。

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


当前回答

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

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

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

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

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

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

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

其他回答

当使用$。ajax函数对服务器的ajax请求,你应该避免使用完整的事件来处理响应数据。无论请求是否成功,它都会触发。

用成功代替完成。

请参阅文档中的Ajax事件。

避免多次搜索整个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();

如果你想让用户在他们的浏览器中看到html实体,使用'html'而不是'text'来注入Unicode字符串,例如:

$('p').html("Your Unicode string")

误解在正确的上下文中使用此标识符。例如:

$( "#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.
   })
});

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

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

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