3

この質問は少し2部構成です。まず、タイトルの質問。これが私が持っているものです:

// 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);

});

残念ながら、これには実際の要素自体は含まれず、親のみが含まれます。「これと両親」のような言い方はありますか?

さて、2番目の質問。スタックに追加できなかった場合、その「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());

よろしくお願いします!

4

1 に答える 1

7

.andSelf最初の質問では、次の方法を使用できます。

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

何か注意する必要があります。$crumb変数はlocal-scopedeachであるため、ループの繰り返しごとに初期化されます。

2 番目の質問については、はい、コールバックの仕事をする関数を定義できます。関数eachへの参照を渡すだけで、呼び出す必要はありません (かっこを削除します)。

$(this).parents().each(crumble);
于 2010-04-01T05:20:07.070 に答える