我做了一个快速的小提琴来概括我的问题:http://jsfiddle.net/mYdxw/
我试图点击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();
});
});<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>发布于 2012-01-16 23:04:40
这..。
$('.itemLinks [data-category=' + target_category + ']').show();应该是这个..。
$('.itemLinks[data-category="' + target_category + '"]').show();空格被解释为子代选择器,但data-category直接位于itemLinks元素上,而不是子代元素上。
我还在属性选择器的值周围添加了引号。API需要它。
演示: http://jsfiddle.net/mYdxw/11/
发布于 2012-01-16 23:17:25
为了改进代码,jQuery提供了.data()来检索数据集的值,而不是使用attr()使用data()
var target_category = $(this).data('target_category');演示:http://jsfiddle.net/mYdxw/28/
https://stackoverflow.com/questions/8887518
复制相似问题