javascript jQuery 等价于 querySelector
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9999504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery equivalent of querySelector
提问by Christophe
What is the jQuery equivalent of querySelector? The only way I've found so far is to select all then pick the first selection:
querySelector 的 jQuery 等价物是什么?到目前为止,我发现的唯一方法是全选,然后选择第一个:
$(selectorString)[0]
With the above expression, is jQuery smart enough to stop after finding the first match?
有了上面的表达式,jQuery 是否足够聪明,可以在找到第一个匹配项后停止?
Update: @Mutnowski suggested using eq() and first, but after reading the jQuery documentation those two methods seem to have the same drawback: jQuery will first get all matches, then only filter out the first element.
更新:@Mutnowski 建议使用 eq() 和 first,但在阅读 jQuery 文档后,这两种方法似乎有相同的缺点:jQuery 将首先获取所有匹配项,然后只过滤掉第一个元素。
采纳答案by Christophe
So it seems that there is no equivalent of querySelector in jQuery, or in other libraries I've looked at.
因此,在 jQuery 或我看过的其他库中,似乎没有与 querySelector 等效的东西。
The workaround is to select all matching elements (equivalent to querySelectorAll) then filter out the first one. This can be done using [0] (returns a html node) or as suggested by @Mutnowski with eq(0) or first (returning a jQuery object).
解决方法是选择所有匹配的元素(相当于 querySelectorAll)然后过滤掉第一个。这可以使用 [0] (返回一个 html 节点)或按照@Mutnowski 的建议使用 eq(0) 或 first (返回一个 jQuery 对象)来完成。
回答by Murtnowski
You want .eq(index) to get an index
你想要 .eq(index) 得到一个索引
$("td").eq(2)
$("td:eq(2)")
If you want just the first use .first()
如果你只想第一次使用 .first()
$("tr").first()
$("tr:first")
回答by Killy
you can write a simple plugin (compatibility notes)
你可以写一个简单的插件(兼容性说明)
$.fn.firstMatch = function(sel) {
var len = this.length;
if (!len) return this;
for(var i = 0; i < len; i++){
var match = this[i].querySelector(sel);
if (match) return $(match);
}
return $();
}