jQuery 数据属性点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8887518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:12:19  来源:igfitidea点击:

jQuery data attribute click event

jquery

提问by benhowdle89

I have made a quick fiddle to outline my problem: http://jsfiddle.net/mYdxw/

我做了一个快速小提琴来概述我的问题:http: //jsfiddle.net/mYdxw/

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

我正在尝试单击一个 div,获取其数据属性并显示其相应的一组 div。

Can anyone spot why it isn't doing this currently?

任何人都可以发现为什么它目前不这样做吗?

JS

JS

$(document).ready(function() {

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

HTML

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>

回答by

This...

这个...

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

should be this...

应该是这个...

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

The space is interpreted as a descendant selector, but the data-categoryis directly on the itemLinkselement, not on a descendant.

空格被解释为后代选择器,但data-category是直接在itemLinks元素上,而不是在后代上。

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

我还在属性选择器的值周围添加了引号。API 需要它。

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

演示:http : //jsfiddle.net/mYdxw/11/

回答by Abhi

Just to improve on the code, jQuery provides .data() to retrieve the value of the dataset so instead of using attr() use data()

只是为了改进代码,jQuery 提供了 .data() 来检索数据集的值,因此使用 data() 代替 attr()

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

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

演示:http: //jsfiddle.net/mYdxw/28/