JQuery data attribute click event

I quickly described my problem: http://jsfiddle.net/mYdxw/

I am trying to click on a div, grab its data attribute and show its corresponding set of divs.

Can anyone understand why he is not doing this now?

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>
+5
source share
2 answers

It...

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

should be ...

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

The space is interpreted as a descendant selector, but data-categoryis located directly on the element itemLinks, and not on the descendant.

I also added quotes around the value of the attribute selector. The API requires this.

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

+11
source

, jQuery .data() , attr() ()

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

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

+11

All Articles