2012-01-16 59 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-putting-code-in-the-question – 2012-01-16 23:05:25

回答

11

這...

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

應該是這樣的......

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

的空間被解釋爲後代選擇,但data-category直接是itemLinks元素上,而不是一個後代。

我還添加了周圍的屬性選擇的值引號。 API需要它。

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

11

只是爲了提高對碼,jQuery提供。數據()來檢索數據集的值,從而代替使用attr的()的使用數據()

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

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

+0

以任何方式這更好的? – benhowdle89 2012-01-16 23:37:32

+0

上面的代碼是HTML 5的努力,使生活更容易developers.http兼容和jQuery努力://tutorialzine.com/2010/11/jquery-data-method/ – Abhi 2012-01-16 23:44:06

+0

@ benhowdle89:它所做的就是將數據導入到屬性jQuery的'.data()'系統。如果你所要做的只是讀取數據,它確實沒有什麼區別。由於您已經在使用'data-'屬性,因此您已經符合HTML5。 jQuery實際上並不使用HTML5'dataset'屬性來讀取數據。但是在有足夠的瀏覽器支持它之後,您可以執行'this.dataset.target_category'來檢索數據。 – 2012-01-16 23:54:47