Cha*_*per 2 jquery show-hide custom-data-attribute
我想通过数据属性而不是类来使用这个show/hide函数,但是我很难获得正确的语法.
我知道它是这样的,$("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;
});
Run Code Online (Sandbox Code Playgroud)
请看一下这个小提琴的工作示例: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;
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,您将小提琴中的"全部"与"全部"进行比较,这是不匹配的.