我正在尝试使用自定义数据属性通过下拉选择来过滤内容。我似乎无法让选择器正常工作,只是想知道这是否真的可能。目前正在看https://api.jqueryui.com/data-selector/ https://api.jqueryui.com/data-selector/但我似乎无法让它发挥作用。
My HTML:
<div class="item-filter">
<form>
<select id="item-filter-select">
<option value="all" id="all">Show All</option>
<option value="clothes" id="clothes">Clothing</option>
<option value="jewelry" id="jewelry">Jewelry</option>
<option value="misc" id="misc">Miscellaneous</option>
</select>
</form>
</div>
<div class="item-display" id="item-display">
<div class="item clothes" id="item-clothes" data-type="clothes" data-name="Sweater01" data-price="15">
<span>Clothes</span><br>
<a href="#" class="add-item" id="item01">Add to Cart</a>
</div>
<div class="item jewelry" id="item-jewelry" data-type="jewelry" data-name="Necklace01" data-price="5">
<span>Jewelry</span><br>
<a href="#" class="add-item" id="item02">Add to Cart</a>
</div>
<div class="item misc" id="item-misc" data-type="misc" data-name="PhoneCase01" data-price="10">
<span>Misc</span><br>
<a href="#" class="add-item" id="item03">Add to Cart</a>
</div>
<div class="clear"></div>
</div>
My JS:
$( document ).ready(function() {
// Handler for .ready() called.
$('#item-filter-select').change(function() {
var clothes = $( "div:data(type, clothes)" );
if($(this).val() === 'clothes'){
clothes.hide();
console.log("You selected clothes");
}
else if($(this).val() === 'jewelry'){
console.log("You selected jewelry");
}
else if($(this).val() === 'misc'){
console.log("You selected miscellaneous");
}
else {
console.log("You are showing all");
}
});
});
我只想隐藏与“selected”数据类型关联的元素(我最终将使用 :not 选择器来隐藏不匹配的元素),但现在我只需要让选择器正常工作。感谢您的任何帮助!
只需直接使用 select 值来定位具有正确数据属性的元素
$(document).ready(function () {
$('#item-filter-select').on('change', function () {
if (this.value == 'all') {
$('.item').show();
}else{
var elems = $('.item[data-type="'+this.value+'"]');
$('.item').not(elems).hide();
elems.show();
}
});
});
FIDDLE http://jsfiddle.net/adeneo/ZjKnw/
或上述内容的较短版本
$(document).ready(function () {
$('#item-filter-select').on('change', function () {
var elems = this.value == 'all' ? $('.item') : $('.item[data-type="'+this.value+'"]');
$('.item').not(elems.show()).hide();
});
});
FIDDLE http://jsfiddle.net/adeneo/ZjKnw/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)