$("li ul span").show();
$("li ul span").toggleClass("bubu");
链接很好
$("li ul span").show().toggleClass("bubu");
,记住局部变量中的东西也不错:
var allspans = $("li ul span");
allspans.show();
allspans.toggleClass("bubu");
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");
发布评论
评论(4)
您应该避免的一件事是在每一行中再次使用“易于使用”的选择器,因为选择器的 JavaScript 实现效率不高。当然,jQUery 的人正在优化它,但是我认为你应该尽可能少地使用它。
所以,这是一个不好的做法。
链接很好
,记住局部变量中的东西也不错:
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.
Chaining is good
And remembering things in a local variable is also not bad:
我经常看到两个:
首先,在单击事件中,
id
的访问方式如下:这将创建一个新 jQuery 对象DOM 节点,并且调用一个函数。以下是正确的方法:
注意:您还将看到
$(this).attr('href')
,但这是正确的,因为 jQuery 在浏览器之间标准化它的方式。第二个是将除 DOM 节点之外的任何内容传递到 jQuery 调用的
scope
参数中:这样做根本不会提高速度。当您已经拥有 DOM 元素时,您确实会看到速度提高:
There are two that I see alot:
First, in a click event, the
id
is accessed like this:That creates a new jQuery object around the DOM node, and calls a function. The following is the correct way:
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: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:
James Padolsey 撰写了关于 jQuery 代码异味的一篇优秀文章。我建议阅读它。
James Padolsey has written an excellent article on jQuery code smells. I recommend reading it.
仍然使用旧的文档准备功能:
而不是非常常见的:
这并不是很糟糕,但我向人们展示了新的 api 还没有起来。
Still using the old document ready function:
Instead of the very common:
It's not really bad, but I shows people not getting up with new api's.