如何将范围限制为每个组,以便销售价值反映该组的数量?
jQuery的:
var sales = (function calculateSales(){
$( "h1 small" ).each(function() {
var group = $(this).parent('.group');
var numItems = group.find('.btn').length;
var sold = group.find('.btn.hidden').length;
$(this).text(sold+" of "+numItems+" sold");
});
return calculateSales;
}());
HTML:
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
答案 0 :(得分:2)
var group = $(this).parent('.group');
应为var group = $(this).closest('.group');
.parent()方法仅搜索搜索集的父节点(在这种情况下为small
),因此它只会查看不满足给定选择器的h1
因此它不会退货。
由于您要查看祖先树,请使用.closest()
var sales = (function calculateSales() {
$("h1 small").each(function() {
var group = $(this).closest('.group');
var numItems = group.find('.btn').length;
var sold = group.find('.btn.hidden').length;
$(this).text(sold + " of " + numItems + " sold");
});
return calculateSales;
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>