2012-05-12 8 views
0

すべての親要素の名前を取得するには?すべての親要素の名前を取得するより良い方法はありますか?

$(document).on('click', function(e){ 
    var parents = $(e.target).parents().map(function(){ 
     var $this = $(this), 
      $id = $this.prop('id') ? '#'+$this.attr('id') : '', 
      $class = $this.prop('class') ? '.'+$this.attr('class') : ''; 
     return this.tagName.toLowerCase()+$id+$class; 
     }).get().join(" < "); 
    prompt('The path to the element, Luke:',parents); 
}); 

FIDDLEを例とします。

EDIT:ニース!みんなありがとう! FIDDLEを更新しました。

+0

あなたは別の方法は、すべての親を取得したいのはなぜ要素??あなたの道はうまくいかない? :\ – elboletaire

+0

私のやり方でさえ常に良い方法があります;) –

答えて

1

は、私はいくつかのテストを実行したと誰もあなたの現在の方法を改善するようになったん。

さらに、gion_13の提案に加えて、要素の表示順序を逆にすることをお勧めします。

あなたの目標に応じて、それは.reverse()を使用して、要素をクリックしてHTMLから読みやすくしている可能性がありますが:

$(document).on('click', function(e){ 
    var parents = $(e.target).parents().map(function(){ 

    var $this = $(this), 
     $id = $this.prop('id') ? '#'+$this.attr('id') : '', 
     $class = $this.prop('class') 
        ? '.'+$.trim($this.attr('class')).replace(/\s+/g,'.') 
        : ''; 

    return this.tagName.toLowerCase()+$id+$class; 

    }).get().reverse().join(" > "); 

    prompt('The path to the element, Luke:',parents); 
}); 

フィドル例here!

3

これは正常に動作し、かなり明確です&ストレートフォワード。各クラスの前にドットを追加し、あなたが改善することができる唯一の事:

$class = $this.prop('class') 
      ? '.'+$.trim($this.attr('class')).replace(/\s+/g,'.') 
      : ''; 

ここでライブデモです:それがうまく機能http://jsfiddle.net/cdWXN/1/

関連する問題