What's the meaning of the comma in a jQuery selector [duplicate]

痞子三分冷 提交于 2019-12-17 18:27:06

问题


<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?

return $('strong', this).length == 2;

What will happen if I remove the word 'strong'?


回答1:


It sets this as the context from which the query is performed.

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:

return $(this).find('').length == 2;

Looks like it just returns an empty jQuery object, which means length will be 0, so you won't get any elements out of the .filter().


Reference:

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

jQuery( selector [, context ] )

context

Type: Element or jQuery

A DOM Element, Document, or jQuery to use as context




回答2:


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.



来源:https://stackoverflow.com/questions/4543336/whats-the-meaning-of-the-comma-in-a-jquery-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!