2010-08-16 146 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(),實際上它會更有效地做到這一點。