2010-08-16 69 views
10

我正在看教程中的一些代码来创建一个轮播菜单,并注意到没有父母的父子选择器。之前从来没有见过这样的事情,并且对它实际上在做什么感到困惑。没有父母的jQuery的儿童选择器

见下面的代码:

 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/

回答

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?

1
$('> div', this) 

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

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

the documentation for $()更多的信息它特别提到这一点:

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

$(this).find('> div')的意思是” div S中的的this,这等于$(this).children('div')孩子

7

此选择与上下文:

$('> div', this) 

被翻转周围使用.find()这样:

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

wh ICH与> child-selector就是:

$(this).children('div') 

其他人也在做同样的交易,他们可以使用.children(),实际上它会更有效地做到这一点。