我有三个input
字段 type:number
当按下按钮时,所有这些都会被单独调用。
例如,我点击button1
然后dialog1
出现等等..
我想要在代码后面( jQuery
)中执行的操作是从数字输入中获取值并将其放入 <div class="total-price"></div>
中
<div id="dialog1">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog2">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog3">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
jQuery
$(".amount").change(function(){
price = 9.99;
amount = $(".amount").val()
total = price * amount;
$(".total-price").html("Totaal: € " + total);
});
这工作正常,但它改变了所有 .total-price
divs...我可以使用 id
但我来这里不是为了id="amount1"
, id="amount2
“,id="amount3"
太乱了。
最佳答案
尝试.siblings()
并将 $('.amount').val()
更改为 $(this).val()
(以获取所引用的输入值)
$(".amount").change(function(){
price = 9.99;
amount = $(this).val()
total = price * amount;
$(this).siblings(".total-price").html("Totaal: € " + total);
});
$(".amount").change(function(){
price = 9.99;
amount = $(this).val()
total = price * amount;
$(this).siblings(".total-price").html("Totaal: € " + total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog1">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog2">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
<div id="dialog3">
<h2>Product 1</h2>
<input type="number" class="col-md-4 amount" id="amount" min="0" max="10" step="1" value="0">
<div class="total-price">Total:</div>
</div>
关于javascript - 多次使用输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29390187/