javascript jQuery 选择器中逗号的含义是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4543336/
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
What's the meaning of the comma in a jQuery selector
提问by dramasea
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<ul>
<li><strong>list</strong> item 1 -
one strong tag</li>
<li><strong>list</strong> item <strong>2</strong> -
two <span>strong tags</span></li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
<script type="text/javascript">
$('li').filter(function(index) {
return $('strong', this).length == 1;
}).css('background-color','red');
</script>
</body>
</html>
Given the HTML above, what's the meaning of the comma in the selector below?
鉴于上面的 HTML,下面选择器中逗号的含义是什么?
return $('strong', this).length == 2;
What will happen if I remove the word 'strong'?
如果我删除“强”这个词会发生什么?
回答by user113716
It sets thisas the context from which the query is performed.
它设置this为执行查询的上下文。
An equivalent (and slightly more efficient) way to write it is:
一种等效(并且稍微更有效)的编写方法是:
return $(this).find('strong').length == 2;
When I say equivalent, I mean behind the scenes, it is actually flipped around into the version above.
当我说等效时,我的意思是在幕后,它实际上是翻转到上面的版本中。
If you remove the 'strong', you won't have a valid selector. You'll be doing:
如果删除'strong',您将没有有效的选择器。你会做:
return $(this).find('').length == 2;
Looks like it just returns an empty jQuery object, which means lengthwill be 0, so you won't get any elements out of the .filter().
看起来它只是返回一个空的 jQuery 对象,这意味着lengthwill 0,所以你不会从.filter().
Reference:
参考:
jQuery( selector [, context ] )
jQuery( 选择器 [, 上下文 ] )
context
语境
Type: Element or jQuery
类型:元素或jQuery
A DOM Element, Document, or jQuery to use as context
用作上下文的 DOM 元素、文档或 jQuery
回答by Nazariy
If you remove STRONG tag, it would check if any of LI contain string 1 character long, regardless if they encapsulated within STRONG tag. In this case no results would be highlighted. Selectors like $('strong', this) and $(this).find('strong') are pretty much the same.
如果删除 STRONG 标签,它会检查 LI 中是否有任何包含 1 个字符长的字符串,无论它们是否封装在 STRONG 标签中。在这种情况下,不会突出显示任何结果。像 $('strong', this) 和 $(this).find('strong') 这样的选择器几乎是一样的。

