【问题标题】:Modify this function to show/hide by data-attributes instead of by class修改此函数以按数据属性而不是按类显示/隐藏
【发布时间】:2013-03-23 09:47:07
【问题描述】:

我想通过数据属性而不是类来使用这个显示/隐藏函数,但是我很难正确地使用语法。

我知道它类似于 $("li[data-color=" + this.value + "]").show();,但我无法让它工作和/或修改函数以使其工作。

我正在使用该功能按各种属性(即颜色、产品类别、场合等)过滤服装,我在这里发布了一个简单的示例:http://jsfiddle.net/chayacooper/WZpMh/4/

$('#filterOptions li a').click(function () {
    var ourClass = $(this).attr('class');
    $('#filterOptions li').removeClass('active');
    $(this).parent().addClass('active');
    if (ourClass == 'all') {
        $('#content').find('.item').show();
    } else {
        $('#content').find('.item:not(.' + ourClass + ')').hide();
        $('#content').find('.item.' + ourClass).show();
    }
    return false;
});

【问题讨论】:

  • 为我工作:jsfiddle.net/awNdC(第 16 行)
  • @valtron - 很高兴知道我的语法是正确的 ;-) 我将如何使用它来按数据属性而不是按类进行过滤?
  • @raphaelvalerio - 我无法为您的帖子投票,因为您已将其删除,但我想大声告诉您我的语法有什么问题(我错过了引号围绕数据颜色属性中的值):-D

标签: jquery show-hide custom-data-attribute


【解决方案1】:

请参阅此小提琴以获取工作示例:http://jsfiddle.net/Cr2cY/

$(document).ready(function () {
    $('#filterOptions li a').click(function () {
        // fetch the class of the clicked item
        var ourDataAttr = $(this).data('color');
        // reset the active class on all the buttons
        $('#filterOptions li').removeClass('active');
        // update the active state on our clicked button
        $(this).parent().addClass('active');
        if (ourDataAttr == 'All') {
            // show all our items
            $('#content').find('.item').show();
        } else {
            // hide all elements that don't share ourClass
            $('#content').find('.item:not([data-color="' + ourDataAttr + '"])').hide();
            // show all elements that do share ourClass
            $('#content').find('.item[data-color="' + ourDataAttr + '"]').show();
        }
        return false;
    });
});

请注意,您在小提琴中将 'all' 与 'All' 进行比较,这将不匹配。

【讨论】:

  • 天啊!那是完美的:-D而且我在小提琴中的错字很糟糕(我把它归咎于我试图弄清楚这一点的头痛;-))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 2013-01-05
  • 2020-05-14
  • 1970-01-01
相关资源
最近更新 更多