我试图创建一个数字字段(.item_adults),将其自身相乘并将值打印到class =" item_price"中。为此,我创建了一些:
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="10" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">10</span></p>
</div>
$( document ).ready(function() {
$(".bookSection").each(function() {
$(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$(".item_price").html(total);
});
});
});
&#13;
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="10" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">10</span></p>
</div>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="15" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">15</span></p>
</div>
</body>
</html>
&#13;
我正在使用:
$(".bookSection").each(function() {
尝试将其分成几部分以独立修改自己的.item_price,但是现在一个部分正在影响其他部分。
希望解释清楚,谢谢!
答案 0 :(得分:4)
使用find()
$(".bookSection").each(function() {
var $item_price = $(this).find(".item_price")
$(this).find(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$item_price.html(total);
});
});
也可以在不需要each
部分的情况下简化这一点:
$(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$(this).closest(".bookSection").find(".item_price").html(total);
});
答案 1 :(得分:2)
关闭,只有几个小小的变化。当你引用$(“。item_adults”)和$(“。item_price”)时,它会影响它们。将范围限制为CURRENT .bookSection,如下所示:
$( document ).ready(function() {
$(".bookSection").each(function() {
$(this).find(".item_adults").change(function(){
var price = ($(this).val());
var ammount = ($(this).attr("data-price"));
var total = (price) * ammount;
$(this).parents(".bookSection").find(".item_price").html(total);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="10" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">10</span></p>
</div>
<div class="bookSection">
<input class="item_adults" name="adults" type="number" data-price="15" value="1" maxlength="2" min="0">
<p>Subtotal: $<span class="item_price">15</span></p>
</div>
</body>
</html>