【问题标题】:Selecting child elements of a specific parent选择特定父元素的子元素
【发布时间】:2013-08-27 06:51:37
【问题描述】:

我有一个有效的代码示例(由其他人编写),但我找不到任何对这种特定语法的引用来解释它为什么有效:

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

这将给我父母的孩子(只有一个),并排除所有其他不来自该父母的 .title 元素。

这是如何/为什么起作用的?

【问题讨论】:

    标签: jquery parent css-selectors


    【解决方案1】:

    参考是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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      相关资源
      最近更新 更多