使用jquery基于自定义数据属性过滤数据

时间:2012-01-23 16:16:18

标签: jquery filtering custom-data-attribute

我想知道是否有人可以帮助使用一些jquery代码来执行以下操作。 我有一个下拉选择列表输入,我想过滤一个复选框列表。

这是我的html代码的样子

 <span style="float:right;">

        <label>Filter</label> 
    <select id="office-type-list" name="OfficeTypes"><option value="00">All</option>

        <option value="05">Township</option>

        <option value="10">Municipality</option>

        <option value="15">Elementary School</option>

        <option value="20">High School</option>

    </select> 

</span>

<!-- List below -->

<div name="Offices">
    <div data-custom-type="00">
        <input type="checkbox" name="Offices" id="Offices_0000" value="0000" /> <label for="Offices_0000">All</label>
    </div>
    <div data-custom-type="05">
        <input type="checkbox" name="Offices" id="Offices_0010" value="0010" /> <label for="Offices_0010">Township 1p</label>
    </div>
    <div data-custom-type="05">
        <input type="checkbox" name="Offices" id="Offices_0020" value="0020" /> <label for="Offices_0020">Township 2</label>
    </div>
</div>

因此,如果选择了乡镇(05),那么只有具有data-custom-type =&#34; 05&#34;的div。将显示。

有没有办法实现这一点,如果有的话,一些帮助将不胜感激

3 个答案:

答案 0 :(得分:7)

您可以执行以下操作:

$("#office-type-list").change(function() {
    var customType = $(this).val();
    $("div[name=Offices]").children("div").hide().filter(function() {
        return $(this).data("custom-type") == customType;
    }).show();
});

上面的代码处理change元素的<select>事件,方法是匹配主<div>元素的直接子元素的Offices元素,将它们全部隐藏,然后应用filter()获取data-custom-type属性与所选值匹配的子项,并显示这些。

答案 1 :(得分:7)

这是一个 jsFiddle 来测试。

$('#office-type-list').change(function(){
    var sel = $(this).val();
    $('div[name="Offices"] div').hide();
    if(sel != "00"){
       $('div[data-custom-type="'+sel+'"]').show();
    }
    else {
        $('div[name="Offices"] div').show();
    }
});

如果选择“全部”,则显示所有选项,否则仅显示匹配的元素。

答案 2 :(得分:4)

试试这个

$("#office-type-list").change(function(){
     $("div[data-custom-type]").hide();
     $("div[data-custom-type=" + this.value +"]").show();
});