jQuery选择器中逗号的含义是什么?

dra*_*sea 28 javascript jquery jquery-selectors

<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>
Run Code Online (Sandbox Code Playgroud)

鉴于上面的HTML,下面的选择器中逗号的含义是什么?

return $('strong', this).length == 2;
Run Code Online (Sandbox Code Playgroud)

如果我删除"强"这个词会怎么样?

use*_*716 53

它设置this为执行查询的上下文.

一种等效(并且稍微更有效)的方式是:

return $(this).find('strong').length == 2;
Run Code Online (Sandbox Code Playgroud)

当我说相当于,我的意思是在幕后,它实际上是翻转到上面的版本.

如果删除'strong',则没有有效的选择器.你会做的:

return $(this).find('').length == 2;
Run Code Online (Sandbox Code Playgroud)

看起来它只是返回一个空的jQuery对象,这意味着length它将是0,所以你不会得到任何元素.filter().


参考:

http://api.jquery.com/jQuery/

jQuery(selector [,context])

上下文

输入:Element或jQuery

用作上下文的DOM元素,文档或jQuery

  • `.filter()`运行你提供的选择器对照jQuery对象中的set,返回一个只有那些匹配的元素的新集合.在你的例子中,`$('p')`将选择文档中的所有`<p>`元素.`.filter(".selected,:first")`会将该集合减少为具有`selected`类的集合,并且是集合中的`:first`.因为你正在使用`:first`,所以你只能获得一个匹配(集合中的第一个)并且只有它具有`selected`类. (2认同)