Jquery Bad practices [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
开发者_C百科Closed 9 years ago.
Improve this questionWhat are the JQuery bad/worst practices you have seen, written or thing should be avoided?
A thing you should avoid is using the "easy to use" selectors in every line once again, because the JavaScript implementation of selectors is not that efficient. Of course, the jQUery guys are optimizing it, however I think you should use it as little as possible.
So, this is a bad practice.
$("li ul span").show();
$("li ul span").toggleClass("bubu");
Chaining is good
$("li ul span").show().toggleClass("bubu");
And remembering things in a local variable is also not bad:
var allspans = $("li ul span");
allspans.show();
allspans.toggleClass("bubu");
There are two that I see alot:
First, in a click event, the id
is accessed like this:
$("a").click(function(e){
var id = $(this).attr('id');
});
That creates a new jQuery object around the DOM node, and calls a function. The following is the correct way:
$("a").click(function(e){
var id = this.id;
});
Note: That you will also see $(this).attr('href')
, but that is correct because of the way jQuery normalizes it across browsers.
The second is passing anything except a DOM node into the scope
parameter of the jQuery call:
$(".child", $(".parent")).doSomething();
// or
$(".child", ".parent").doSomething();
There is no speed gain at all by doing this. Where you do see a speed increase, is when you already have the DOM element:
$('div').click(function(){
$('img', this).doSomething(); // This is good
});
James Padolsey has written an excellent article on jQuery code smells. I recommend reading it.
Still using the old document ready function:
$("document").ready(function(){ });
Instead of the very common:
$(function(){ });
It's not really bad, but I shows people not getting up with new api's.
精彩评论