jQuery选择器中逗号的含义是什么 [英] What's the meaning of the comma in a jQuery selector
问题描述
<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>
鉴于上面的HTML,下面的选择器中的逗号是什么意思?
Given the HTML above, what's the meaning of the comma in the selector below?
return $('strong', this).length == 2;
如果我删除"strong"一词会怎样?
What will happen if I remove the word 'strong'?
推荐答案
它将this
设置为执行查询的上下文.
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.
如果删除'strong'
,将没有有效的选择器.您将要做的:
If you remove the 'strong'
, you won't have a valid selector. You'll be doing:
return $(this).find('').length == 2;
看起来它只是返回一个空的jQuery对象,这意味着length
将是0
,因此您不会从.filter()
中获取任何元素.
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()
.
参考:
jQuery(选择器[,上下文])
jQuery( selector [, context ] )
上下文
类型:元素或jQuery
Type: Element or jQuery
用作上下文的DOM元素,文档或jQuery
A DOM Element, Document, or jQuery to use as context
这篇关于jQuery选择器中逗号的含义是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!