【问题标题】:jquery child selector without parent没有父母的jquery子选择器
【发布时间】:2011-03-30 16:45:45
【问题描述】:

我正在查看创建轮播菜单的教程中的一些代码,并注意到没有父级的父子选择器。以前从未见过这种情况,并且对它实际上在做什么感到困惑。

见以下代码:

        var $wrapper = $('> div', this).css('overflow', 'hidden'),
        $slider = $wrapper.find('> ul'),
        $items = $slider.find('> li'),
        $single = $items.filter(':first'),

        singleWidth = $single.outerWidth(), 
        visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
        currentPage = 1,
        pages = Math.ceil($items.length / visible);

教程在这里:http://jqueryfordesigners.com/jquery-infinite-carousel/

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:
    $('> div', this)
    

    this 很重要。它是一个上下文参数,使查询等于

    $(this).children('div');
    

    更多信息请见the documentation for $();它特别提到了这一点:

    在内部,选择器上下文是 使用 .find() 方法实现, 所以$('span', this) 相当于 $(this).find('span').

    $(this).find('> div') 表示“divs 是 this 的子代,等于 $(this).children('div')

    【讨论】:

      【解决方案2】:

      这个带有上下文的选择器:

      $('> div', this)
      

      像这样使用.find()

      $(this).find('> div')
      

      > child-selector 只是:

      $(this).children('div')
      

      其他人也在做同样的事情,他们可以使用.children(),实际上这样做会更有效率。

      【讨论】:

        【解决方案3】:

        有一个父级(或在本例中为scope),请注意选择器内的this 关键字,它与应用插件的元素相关。

        jQuery 的选择器允许你设置一个范围,它可以是任何 jQuery 元素对象。

        考虑

        $(".somediv").myplugin();
        

        在插件内部

        $("> div", this) 
        is actually translated to 
        $("> div", $(".somediv"))
        

        看看我的一个问题,答案解释了很多关于 jQuery 选择器的信息。 What is the fastest method for selecting descendant elements in jQuery?

        【讨论】:

          猜你喜欢
          • 2014-05-15
          • 2011-06-23
          • 2011-04-27
          • 1970-01-01
          • 1970-01-01
          • 2011-04-28
          • 1970-01-01
          • 1970-01-01
          • 2011-01-23
          相关资源
          最近更新 更多