【问题标题】:Jquery what is the difference between .find and simply a space between ancestor and descendant?Jquery .find 和简单的祖先和后代之间的空格有什么区别?
【发布时间】:2013-09-26 13:19:08
【问题描述】:

$("div .product"); 选择具有 div 祖先的 product 类的元素 据我所知,$("div").find(".product"); 的作用完全相同。

两者都适合我。 我想知道应该使用哪个来简化我的代码?

【问题讨论】:

    标签: jquery jquery-selectors find ancestor descendant


    【解决方案1】:

    如果您已经有一个带有父元素的 jQuery 对象,则 Find 特别有用:

    var $elements = $("div");
    // some code that does other stuff with $elements
    // ...
    // then
    var $products = $elements.find(".product");
    

    或者即使您直接引用了作为父/祖先的 DOM 元素:

    $(domElementRef).find(".product");
    // or inside an event handler where 'this' is the DOM element the event applied to:
    $(this).find(".product");
    

    如果您不需要对父/祖先元素进行任何类型的处理,只需将组合选择器与 $("div .product") 一起使用即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-22
      • 2015-09-14
      • 2018-11-05
      • 2015-08-19
      • 1970-01-01
      • 2010-11-16
      • 2016-11-29
      • 2017-03-19
      相关资源
      最近更新 更多