【发布时间】:2014-03-27 20:59:21
【问题描述】:
我正在尝试使用自定义数据属性通过下拉选择过滤事物。我似乎无法让选择器正常工作,只是想知道这是否真的可能。目前正在查看https://api.jqueryui.com/data-selector/,但我似乎无法让它工作。
我的 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>
我的 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");
}
});
});
我只想隐藏与“选定”数据类型关联的元素(我最终将使用 :not 选择器来隐藏不匹配的元素),但现在我只需要让选择器正常工作。感谢您的帮助!
【问题讨论】:
-
"如果表达式
$( "div:data(foo)")具有通过.data( "foo", value )存储的数据,则它与<div>匹配。" 由于您没有以这种方式存储数据,这可能是它不起作用的原因。我不确定 jQuery 何时/如何准确地将data-*属性放入.data。如果您只关心数据 attributes 的值,则可以使用简单的属性选择器。 -
你可以使用
var clothes = $( "div[data-type]" ); -
“我只想隐藏与所选数据类型相关的元素” - is this what you mean?
标签: javascript jquery html jquery-ui