jQuery - 根据锚标记过滤div(单击)

时间:2013-07-06 10:22:27

标签: ajax jquery

假设我有10个div元素,类 .hide ,它有不同的类别名称(例如食物,旅行,运动....) div内容。

<div id="Categories">
    <div class="hide">Foods are Fruits, Chicken, Rice, Pizza...</div>
    <div class="hide">My Travelling places are Bangalore, Goa, Kolkata..</div>
    <div class="hide">Sports :Cricket, Basket ball, Tennis, ..</div>
          .
          .
</div>

并说我有3个锚标记,

<a href="#">Food</a>
<a href="#">Travelling</a>
<a href="#">Sports</a>
         .
         .

所以,我想用尊重的类别过滤这些div.hide元素。

我使用复选框进行了相同的过滤,

<script>
    var $filters = $("input:checkbox[name='fli']"); 

var $categoryContent = $('#Categories .hide');
var $errorMessage = $('#errorMessage');
$filters.click(function() {
    // if any of the checkboxes for Category or team are checked, you want to show div's containing their value, and you want to hide all the rest.
    $categoryContent.hide();
     var $selectedFilters = $filters.filter(':checked');
    if ($selectedFilters.length > 0) {
        $errorMessage.hide();
        $selectedFilters.each(function (i, el) {
            $categoryContent.filter(':contains(' + el.value + ')').show();
        });
    } else {
        $errorMessage.show();
    }

});
</script>

但我也想要这个,

我如何实现这一目标,请任何人帮助我。

由于

1 个答案:

答案 0 :(得分:0)

可以这样做:

DEMO

$('.nav a').on('click', function (e) {
    e.preventDefault();
    var cat = $(this).data('categoryType');
    $('#Categories > div').addClass('hide')
    $('#Categories > div[data-category-type="'+cat+'"]').removeClass('hide');
});

HTML:

<div class="nav">
<a href="#" data-category-type="Food">Food</a>

<a href="#" data-category-type="Travelling">Travelling</a>

<a href="#" data-category-type="Sports">Sports</a>

</div>
<div id="Categories">
    <div class="hide" data-category-type="Food">Foods are Fruits, Chicken, Rice, Pizza...</div>
    <div class="hide" data-category-type="Travelling">My Travelling places are Bangalore, Goa, Kolkata..</div>
    <div class="hide" data-category-type="Sports">Sports :Cricket, Basket ball, Tennis, ..</div>
    <div class="hide" data-category-type="Food">Foods are Fruits, Chicken, Rice, Pizza...</div>
</div>