有几个这样的HTML片段。我想点击“check_all”时检查属于 this “shopcart-con”类的“check_item”。但是当我点击“check_all”时,检查了所有“check_item”。怎么解决?感谢
HTML:
<div class="shopcart-con" data-merchant-id="1">
<div class="shopcart-list">
<div class="shopcart-lstop"><input type="checkbox" class="check_all" name="select"/>fruit shop A</div>
<div class="shopcart-lscon">
<ul class="shop_contentul" data-product-id="1">
<li class="checkinp"><input type="checkbox" class="check_item" name="aihao" /></li>
<li class="checkimg"><img src="images/home10.png" width="100%" height="75px"></li>
<li class="checknum" >
<p class="lineheight30">apple</p>
<span class="shopcart-num">
<input type="button" name="" class="inp-reduce">
<input type="text" name="" class="num" value="5">
<input type="button" name="" class="inp-add">
</span>
</li>
¥<span class="unit_price">8.00</span>
<p><font color="#808080" size="2px"><s> $12.00</s></font></p>
<p>x<label class="shuli">5</label></p>
<input class="delbtn" name="">
</ul>
<div class="clear"></div>
</div>
<div class="shopcart-lscon">
<ul class="shop_contentul" data-product-id="2">
<li class="checkinp"><input type="checkbox" class="check_item" name="aihao" /></li>
<li class="checkimg"><img src="images/home10.png" width="100%" height="75px"></li>
<li class="checknum" >
<span class="shopcart-num">
<input type="button" name="" class="inp-reduce">
<input type="text" name="" class="num" value="5">
<input type="button" name="" class="inp-add">
</span>
</li>
¥<span class="unit_price">8.00</span>
<!-- <p><font color="#808080" size="2px"><s> $12.00</s></font></p> -->
<p>x<label class="shuli">5</label></p>
<input class="delbtn" name="">
</ul>
<div class="clear"></div>
</div>
<div>
<p class="shopcart-money">共计<label class="product_quantity" data-merchant-id="1">10</label> sum:$<label class="price_sum" data-merchant-id="1" style="color:red">80</label></p>
</div>
</div>
</div>
JS:
$('.check_all').click(function(){
var checked_items = $('.check_all').closest('.shopcart-con').find('.check_item')
console.log(checked_items.length)
if($(this).prop('checked')){
$.each(checked_items, function(i,val){
val.checked = true;
});
}else{
$.each(checked_items, function(i,val){
val.checked = false;
});
}
});
答案 0 :(得分:1)
试试这个:您正在使用$('.check_all').closest
这将在所有shopcart-con
下找到check_all
。但是,您需要为点击的shopcart-con
找到check_all
,因此请$(this)
使用$(this).closest
$('.check_all').click(function(){
var checked_items = $(this).closest('.shopcart-con').find('.check_item')
console.log(checked_items.length)
if($(this).prop('checked')){
$.each(checked_items, function(i,val){
val.checked = true;
});
}else{
$.each(checked_items, function(i,val){
val.checked = false;
});
}
});
<强> DEMO 强>
您可以使代码更短,您无需迭代所有复选框并设置其属性,请参阅下面的代码
$('.check_all').click(function(){
var checked_items = $(this).closest('.shopcart-con').find('.check_item')
console.log(checked_items.length)
$(checked_items).prop('checked',this.checked);
});
<强> DEMO 强>