zSy*_*sis 6 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>
Run Code Online (Sandbox Code Playgroud)
因此,如果选择了Township(05),则只显示data-custom-type ="05"的div.
有没有办法实现这一点,如果有的话,一些帮助将非常感激
你可以这样做:
$("#office-type-list").change(function() {
var customType = $(this).val();
$("div[name=Offices]").children("div").hide().filter(function() {
return $(this).data("custom-type") == customType;
}).show();
});
Run Code Online (Sandbox Code Playgroud)
上面的代码通过匹配元素的直接子元素,将它们全部隐藏起来然后应用filter()来获取属性与所选值匹配的子元素并显示这些元素来处理元素change事件.<select><div>Officesdata-custom-type
这是一个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();
}
});
Run Code Online (Sandbox Code Playgroud)
如果选择"全部",则显示所有选项,否则仅显示匹配的元素.