gpt4 book ai didi

javascript - 使用 :data attribute as a selector to filter elements

转载 作者:行者123 更新时间:2023-11-28 04:56:16 25 4
gpt4 key购买 nike

我正在尝试使用自定义数据属性通过下拉选择来过滤内容。我似乎无法让选择器正常工作,只是想知道这是否真的可行。目前正在查看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");
}
});

});

我只想隐藏与数据类型“selected”关联的元素(我最终会使用 :not 选择器来隐藏不匹配的元素)但现在我只需要让选择器正常工作。感谢您的帮助!

最佳答案

只需直接使用选择值来定位具有正确数据属性的元素

$(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

或上述的更短版本

$(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

关于javascript - 使用 :data attribute as a selector to filter elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22699072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com