2012-01-16 6 views
5

をクリックして属性私は私の問題の概要を説明するための簡単なバイオリンを作っていますhttp://jsfiddle.net/mYdxw/jQueryのデータは、イベント

私は、divの上でクリックすると、そのデータの属性を取得し、div要素の対応するセットを表示しようとしています。

これは現在行われていない理由は誰にも分かりますか?

JS

$(document).ready(function() { 

    $('.categoryItems').click(function() { 
     $('.itemLinks').hide(); 
     var target_category = $(this).attr('data-target_category'); 
     $('.itemLinks [data-category=' + target_category + ']').show(); 
    }); 
}); 

HTML

<div id="categories"> 
    <div data-target_category="html-site-templates" class="categoryItems">HTML Site Templates</div> 
    <div data-target_category="jquery-plugins" class="categoryItems">jQuery Plugins</div> 
    <div data-target_category="tumblr-themes" class="categoryItems">Tumblr Themes</div> 
    <div data-target_category="wordpress-themes" class="categoryItems">WordPress Themes</div>  
</div> 

<div id="content"> 
    <a class="itemLinks" data-category="tumblr-themes" href="/tumblr-themes/mini-tumblr-theme/">Mini Tumblr Theme</a> 
    <a class="itemLinks" data-category="jquery-plugins" href="/jquery-plugins/randomr-jquery-plugin/">Randomr jQuery Plugin</a> 
    <a class="itemLinks" data-category="wordpress-themes" href="/wordpress-themes/redux-wp-theme/">Redux WP Theme</a> 
</div> 
+3

質問に*関連するコード/マークアップ*を必ず含めてください。理由:http://meta.stackexchange.com/questions/118392/add-stack-overfow-faq-entry-or-similar-for-put-code-in-the-question –

答えて

11

この...

$('.itemLinks [data-category=' + target_category + ']').show(); 

この...

$('.itemLinks[data-category="' + target_category + '"]').show(); 

空間が子孫セレクタとして解釈されるべきであるが、data-categoryitemLinks要素ではなく、子孫の上に直接あります。

また、属性セレクタの値を引用符で囲みました。 APIが必要です。

DEMO:http://jsfiddle.net/mYdxw/11/

11

だけコードを改善するために、jQueryの(.DATAを提供する)代わりに、ATTRを(使用するように、データセットの値を取得するためには)(データを使用)

var target_category = $(this).data('target_category'); 

DEMO:http://jsfiddle.net/mYdxw/28/

+0

これはどのような点でも優れていますか? – benhowdle89

+0

上記のコードは、HTML 5に準拠しており、開発者の方が楽になるようにするためのjQueryの取り組みです.http://tutorialzine.com/2010/11/jquery-data-method/ – Abhi

+0

@ benhowdle89:データ属性をjQueryにインポートするだけです'.data()'システムです。あなたがしようとしているのはデータを読むだけであれば、実際には違いはありません。既に 'data-'属性を使用しているので、すでにHTML5に準拠しています。 jQueryは実際にはデータを読み取るためにHTML5の 'dataset'プロパティを使用しません。しかし、十分なブラウザがそれをサポートすると、 'this.dataset.target_category'を実行してデータを取得することができます。 –