以下标记中最有效的 jQuery 选择器是什么?
我目前有一些第三方客户端“魔法小部件”库,我必须处理它们...:)我真正要做的就是用 jQuery 添加一些少量的行为来适应一些简单的业务规则。很多时候,我发现自己以同样的方式选择一堆元素。由于“神奇小部件”已经非常依赖 JS,而且我什至在我的快速机器上注意到它,所以我试图将自己的 JS 保持在绝对最低限度。那么,假设用户单击以下输入之一,那么使用 jQuery 在以下结构中选择所有输入(包括单击的输入)的最有效方法是什么?
<div>
<label><input ... /></label>
<label><input ... /></label>
<label><input ... /></label>
</div>
I currently have some third party client-side "magic widgets" library that I have to deal with... :) All I have to do really is to add some small amount of behavior to those things with jQuery to accommodate for some simple business rules. A lot of times, I find myself selecting a bunch of elements in the same way. Since "magic widgets" are already super heavy on JS, and I even notice it on my fast machine, I was trying to keep my own JS to an absolute minimum. So, given that the user clicks on one of the following inputs, what is the most efficient way to select all the inputs, including the clicked one, in the following structure with jQuery?
<div>
<label><input ... /></label>
<label><input ... /></label>
<label><input ... /></label>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,您的输入不应包含在标签中,但这是一个不同的论点。
最快的方法可能是:
不过,这也会再次选择您单击的输入。如果这是一个问题,请尝试:
如果您使用正确的标记,以便标签标记位于每个输入元素之前,那么您的 HTML 将如下所示
然后您的 jQuery 代码变得更容易:
First of all, your inputs shouldn't be wrapped in labels, but that's a different argument.
The fastest way is probably:
This will select your clicked input again too, though. If that's a problem, try:
If you were using correct markup so that the label tags preceded each input element, then your HTML would look like
Then your jQuery code becomes way easier:
好吧,假设该标记中没有元素具有唯一的 id 或类名称,那么您可以使用的最有效的选择器是标记名称和
>
的组合,或者first-child
选择器:Well, assuming none of the elements in that markup have unique id's or class names, the most efficient selector you can use is a combination of tag names and the
>
, orfirst-child
selector:$("div>label>input")
我想。尽管您可以为每个输入提供一个公共类并执行$("input.class")
。$("div>label>input")
I presume. Although you could give each input a common class and do$("input.class")
.这取决于。如果标记仅由您的片段组成:
所有现代浏览器都有标记缓存。
如果您在
div
中查找输入,请将id
添加到div
:并使用此选择器:
id 很重要,因为它是浏览器可以执行的最快的查询。
it depends. if the markup only consists of your fragment than:
All modern broswers have a cache to tags.
If your looking for the inputs in within the
div
add anid
to thediv
:and use this selector:
The
id
is important since it is the fastest possible query a browser can perform.似乎使用类名比使用没有任何父级的标签名更好。 这里是测试你自己的测试。
也许更复杂的html结构会给出不同的结果。
Seems like using class name better than using tag names without any parent. Here is the test for it for test your self.
Maybe more complex html structure give different results.