帮助理解 jQuery 选择器示例
以下代码取自 timers jQuery 插件演示。我不明白第 2 行的选择器中发生了什么。看起来它正在选择 p 元素,但是逗号后面的第二个参数 - demos
- 是为了什么?
jQuery:
var demos = $("div.wrapper div.demos");
$(".uncontrolled-interval p", demos).everyTime(1000,function(i) {
$(this).html(i);
});
HTML:
<div class="wrapper">
<div class="demos">
<div class="uncontrolled-interval">
<p>I am transient... *sigh*</p>
</div>
</div>
</div>
谢谢
The following code was taking from the timers jQuery plugin demo. I don't understand what is happening in the selector in line 2. It seems it is selecting the p element, but then what is the second argument after the comma - demos
- there for?
jQuery:
var demos = $("div.wrapper div.demos");
$(".uncontrolled-interval p", demos).everyTime(1000,function(i) {
$(this).html(i);
});
HTML:
<div class="wrapper">
<div class="demos">
<div class="uncontrolled-interval">
<p>I am transient... *sigh*</p>
</div>
</div>
</div>
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它指定搜索的上下文。基本上是一个过滤器。
http://api.jquery.com/jQuery#expressioncontext
所以在这个例子中它搜索 <
.uncontrol-interval p
的 code>demos 元素。如果您有此标记,它仍然只会选择demos
中的标记。It specifies the context of the search. Basically a filter.
http://api.jquery.com/jQuery#expressioncontext
So in this example it searches the
demos
element for.uncontrolled-interval p
. If you have this markup, it would still only select the one indemos
.当使用 jQuery 使用
jQuery
函数(或其别名$
)选择元素时,您可以提供上下文以及选择器,如 此处。也就是说:在给定的 context 中选择与所提供的 CSS selector 相匹配的每个元素,其中 context 表示您选择的 DOM 区域已经选择了。
换句话说,它说:使用 context 作为正在搜索的 DOM 树的根,而不是文档根。
When selecting elements with jQuery using the
jQuery
function (or its alias$
), you can provide a context as well as a selector as described here.What that says is: select every element that matches the provided CSS selector within the given context, with context meaning the region of the DOM that you have already selected.
Put another way, it says: use the context as the root of the DOM tree being searched, as opposed to the document root.
除了其他答案之外,上下文的工作方式类似于 .find():
就我个人而言,我更喜欢将
demos.find(".uncontrol-interval p")
写入$(".uncontrol-interval p", demos)
In addition to others answer, context works like .find():
Personnaly, I prefer write
demos.find(".uncontrolled-interval p")
to$(".uncontrolled-interval p", demos)