2010-04-01 39 views
3

此問題有點像兩個人一樣。首先,標題問題。這裏是我得到的:在jQuery中將「this」添加到「each」的父級堆棧中

// Report all of the parents 
$(this).parents().each(function(i){ 

    // Collect the parts in a var 
    var $crumb = ''; 

    // Get the tag name of the parent 
    $crumb += "<span class='tagName'>"+this.tagName+"</span>"; 

    // And finally, report it 
    $breadcrumbs.prepend($crumb); 

}); 

不幸的是,這不包括實際的元素本身,只包括父母。有沒有什麼方法可以說「這個和父母」?

現在,第二個問題。如果我無法添加到堆棧中,我將如何將該函數的內容分離爲另一個函數,同時保留它的「this」能力?它會是這樣的:

// Function to report the findings 
function crumble(e){ 

    // Collect the parts in a var 
    var $crumb = ''; 

    // Get the tag name of the parent 
    $crumb += "<span class='tagName'>"+this.tagName+"</span>"; 

    // And finally, report it 
    $breadcrumbs.prepend($crumb); 

}; 
$(this).parents().each(crumble()); 

在此先感謝您的時間!

回答

7

對於第一個問題,你可以使用.andSelf方法:

$(this).parents().andSelf().each(function() { 
    // .. 
}); 

你必須要注意的東西時,$crumb變量是局部範圍的,所以它會在你的每一次迭代each環路初始化。

關於第二個問題,是的,你可以定義是否each回調的作業的功能,你只需要傳遞給它的一個參考,而不是調用它(去掉括號):

$(this).parents().each(crumble); 
+0

不錯!謝謝。你能推薦一個引用來調用/不調用函數(如crumble)嗎?我想了解更多=) – Matrym 2010-04-01 05:25:23

+0

哦,這裏有一個關於您的解決方案的有趣的小事實。它顛倒了堆棧的順序!很容易用reverse()或append(而不是prepend)來解決。 – Matrym 2010-04-01 05:27:00