我正在尝试建立一个函数,当在inputs
中更改两个.item
时计算总数。我希望仅在每个inputs
上的.item
上发生这种情况,但是目前,我对{{1 }}
calculateTotal()
.item
keyup
答案 0 :(得分:1)
使用item.find(".totalprice").text(total)
function calculateTotal() {
$(".item").each(function() {
var item = $(this);
var qty = item.find(".qty").val();
var price = item.find(".cost").val();
var total = Number(qty) * Number(price);
item.find(".totalprice").text(total)
});
}
calculateTotal();
$(document).keyup('.input--item',function() {
calculateTotal();
});
.item {
display: flex;
align-items: center;
}
.wrap {
border: 2px solid #eee;
display: flex;
flex-direction: column
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="wrap">
Cost:
<div class="edit">
<input class="input--item qty" type="text" name="name" autocomplete="off" value="12" maxlength="3" />
</div>
Price:
<div class="edit">
<input class="input--item cost" type="text" name="name" autocomplete="off" value="55" maxlength="4" />
</div>
</div>
<span class="totalprice"></span><br>
</div>
<div class="item">
<div class="wrap">
Cost:
<div class="edit">
<input class="input--item qty" type="text" name="name" autocomplete="off" value="40" />
</div>
Price:
<div class="edit">
<input class="input--item cost" type="text" name="name" autocomplete="off" value="79" />
</div>
</div>
<span class="totalprice"></span><br>
</div>
答案 1 :(得分:0)
这里您要更改所有div的文本,而必须更改当前项目的div,就像这样
function calculateTotal() {
$(".item").each(function() {
var item = $(this);
var qty = item.find(".qty").val();
var price = item.find(".cost").val();
var total = Number(qty) * Number(price);
$(this).find(".totalprice").text(total);
});
}
calculateTotal();
$(".input--item").on("input",function() {
calculateTotal();
});
.item {
display: flex;
align-items: center;
}
.wrap {
border: 2px solid #eee;
display: flex;
flex-direction: column
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="wrap">
Cost:
<div class="edit">
<input class="input--item qty" type="text" name="name" autocomplete="off" value="12" maxlength="3" />
</div>
Price:
<div class="edit">
<input class="input--item cost" type="text" name="name" autocomplete="off" value="55" maxlength="4" />
</div>
</div>
<span class="totalprice"></span><br>
</div>
<div class="item">
<div class="wrap">
Cost:
<div class="edit">
<input class="input--item qty" type="text" name="name" autocomplete="off" value="40" />
</div>
Price:
<div class="edit">
<input class="input--item cost" type="text" name="name" autocomplete="off" value="79" />
</div>
</div>
<span class="totalprice"></span><br>
</div>