jQuery简单复选框隐藏和显示div(产品过滤) [英] jQuery simple checkbox to hide and show divs (product filtering)
问题描述
我正在使用jQuery来过滤页面上的产品项目(隐藏和显示DIV)我使用过滤器作为替代品,因为PHP $ _GET有点旧,我们正试图通过jQuery来做到这一点。我使用filter()和data属性。
I am using jQuery to filter product items on a page (hide and display DIVs) I am using filter as a replacement since PHP $_GET is a bit old fashion we're trying to do this via jQuery. I using filter() and data attribute.
如何关闭除现有项目之外的当前复选框选项?
我如何根据选择隐藏项目,何时不隐藏?
How can I turn off the current selection of checkboxes except the existing item? How can I hide the items based off selection and unhide when not?
<input type="checkbox" id="drama" onClick="filterCategory(this.value)" value="drama" /> Drama<br />
<input type="checkbox" id="romance" onClick="filterCategory(this.value)" value="" /> Romance<br />
<input type="checkbox" id="horror" onClick="filterCategory(this.value)" value="horror" /> Horror<br />
<!--------------------->
<div class="products">
<div class="productItem" data-price="250" data-category="horror">
Scary Book
<div class="productItemPrice"><span>£250</span></div>
</div>
<div class="productItem" data-price="150" data-category="drama">
Drama Poems
<div class="productItemPrice"><span>£150</span></div>
</div>
<div class="productItem" data-price="250" data-category="romance">
Love Story
<div class="productItemPrice"><span>£250</span></div>
</div>
<div class="productItem" data-price="241" data-category="horror">
Creep Book
<div class="productItemPrice"><span>£241</span></div>
</div>
</div>
<!--------------------->
jQUERY
jQUERY
function filterCategory(id) {
var pid=$(".productItem"); // Which product is it
var checkid=$('#'+id); // The name of the checkbox form
var cid=$(pid).data("category"); // The value of the checkbox form
if ($(checkid).is(':checked')){
$(pid).hide().filter(function () {var catId=$(this).data("category");return catId;}).show();
} else {
$(pid).show().filter(function () {var catId=$(this).data("category");return catId;}).show();
}
}
CSS
CSS
.productItem{float:left;padding:5px;margin:5px;border:1px solid #eaeaea}
body{font-family:verdana}
JSFiddle
推荐答案
您可以尝试使用类似的东西,
You could try using something like this instead,
首先删除复选框上的 onclick
属性 - 使用jQuery绑定单击
事件:
Firstly remove the onclick
attribute on the checkboxes - use jQuery to bind the click
event :
// bind to click
$('input[type="checkbox"]').click(function() {
// any checked
if ($('input[type="checkbox"]:checked').length > 0) {
// hide all
$('.products >div').hide();
// loop checked and display relavent div
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
});
} else {
// none checked - show all
$('.products >div').show();
}
});
这篇关于jQuery简单复选框隐藏和显示div(产品过滤)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!