选择特定父级的子元素

时间:2013-08-26 22:49:41

标签: jquery parent css-selectors

我有一个代码示例(由其他人编写),但是我找不到任何对这个特定语法的引用来解释它的工作原理:

var parent = $("#theParentDiv");
var child = $(".title", parent);

这将为我提供父项的子项(只有一项),并排除不从此父项下降的所有其他.title元素。

这是如何/为何有效?

1 个答案:

答案 0 :(得分:3)

引用为here, in the documentation。第二个参数被文档称为“上下文”。

这很有效,因为jQuery将调用转换为对find的调用。

此:

var child = $(".title", parent);

成为这个:

var child = $(parent).find(".title");

...只查找与选择器匹配的元素,如果它们是父级的后代。

在1.10.2未缩小的jQuery脚本中,这发生在第202行,如下所示:

return this.constructor( context ).find( selector );