2011-08-13 14 views
1

開いているコンテンツのセクションのdiv idへのリンクを結びつけるために、メニューリンクのリストでhtmlのdata-attributeを使用しますリンクがクリックされたとき。だから私は "#section1"と呼ばれる隠されたdivを持っている - そのリンクを開くリンクです。jquery - 別の要素のデータ属性に一致するIDを持つ要素を見つける最良の方法

現在、このリンクに一致するdivを見つけるために、jquery .each()を使用してすべての要素をループしますが、より良い方法があるようです。

誰でもこのコードを合理化し、ループ内のコードを実行することなく一致する要素を見つける方法を知っていますか?すべて一緒に

$('a.hidden_link').click(function(){ 
    section_ident = $(this).attr('data-ident'); 
    $('.hidden_section').each(function(index) { 
     if ($(this).attr('data-ident') == section_ident){ 
      section_ref = $(this); 
      section_ref.show(); 
     } 
    }); 
}); 
+0

私は正しいですが、この$( '#' + section_indent)を試すことができます – Shadow

答えて

2

これは動作するはず

は、ここに私のコードです。

$('a.hidden_link').click(function(){ 
    $(".hidden_section[data-ident='"+$(this).attr('data-ident')+"']").show(); 
}); 

Jsfiddle、http://jsfiddle.net/playerace/H7jwb/

1
$('.hidden_section[data-ident="' + section_ident + '"]').show(); 

$('a.hidden_link').click(function(){ 
    var section_ident = $(this).attr('data-ident'); 
    $('.hidden_section[data-ident="' + section_ident + '"]').show(); 
}); 
+0

'section_ident'ではありませんか?修正してください:-) – andyb

0

これはjQuery.filter()のための仕事のように聞こえます!

$('a.hidden_link').click(function(){ 
    var section_ident = $(this).data('ident'); 
    $('.hidden_section').filter(function() { 
     return this.attributes["data-ident"] == section_ident; 
    }).show(); 
}); 
+0

フィルタを1つのステップで実行できるときは、なぜそれをすべて見つけるのでしょうか? – epascarello

+0

http://jsfiddle.net/P9r9B/1/ - Chromeでは高速ですが、FFでは遅くなります。 – Chris

+0

この場合、フィルタを使用する理由はありません。 – Chris

関連する問題