多次使用输入

Use inputs multiple times

本文关键字:输入      更新时间:2023-09-26

我有三个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: &euro; " + total);
  });

这很好用,但它改变了所有.total-pricedivs。。。我可以使用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: &euro; " + total);
  });

$(".amount").change(function(){
    price = 9.99;
    amount = $(this).val()
    total = price * amount;
    $(this).siblings(".total-price").html("Totaal: &euro; " + 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>

由于输入和div在同一级别,您可以从jQuery中使用siblings()

$(".amount").change(function() {
    price = 9.99;
    amount = $(this).val(); //This will get the value from the current input
    total = price * amount;
    $(this).siblings(".total-price").html("Total: &euro;"+total);
});

当您在元素内部时,需要使用this来引用该元素。

在jquery 中使用.next()

$(this).val(); //to get current input 
$(this).next().html("Totaal: &euro; " + total);

更改行

amount = $(".amount").val()
$(".total-price").html("Totaal: &euro; " + total);

amount = $(this).val(); 
$(this).parent().find(".total-price").html("Totaal: &euro; " + total);