gpt4 book ai didi

javascript - 使用 jQuery 添加新输入字段时如何计算总数

转载 作者:行者123 更新时间:2023-11-28 14:36:13 25 4
gpt4 key购买 nike

$(document).ready(function(){

$(".price2").keyup(function(){
total = parseInt($(".price1").val()) + parseInt($(".price2").val());
$(".total").val(total);
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="price1" >
<input type="text" class="price2" >
<input type="text" class="total" >

此代码片段执行两个字段的加法并将总计添加到第三个字段。好吧,这看起来不错,但问题是当我使用 jQuery 添加新字段时,所以完全不起作用。即使我使用 jQuery 添加新的输入字段,我应该怎么做才能添加总计

通过下面的图片您可以更好地理解 enter image description here

我通过以下代码添加新字段

var i = 0;
$("#addmore").click(function() {
$("#inputtabletable tr:first").clone().find(".webfield").each(function() {
$(this).val('').attr({
'id': function(_, id) {
return id + i
},
'name': function(_, name) {
return name + i
},
'value': ''
});
}).end().appendTo("#inputtabletable");
i++;
});

使用 jQuery 添加新字段时如何添加总计

最佳答案

您的用例需要对 html 和 javascript 进行一些更改,它无法开箱即用。您需要利用事件委托(delegate)并从将来创建的元素捕获事件。

有关代表的更多信息可以在此处找到 jQuery .on

$(document).ready(function() {

$('.addition').on('keyup', '.price', function() {
var total = 0
$('.addition > .price').each(function() {
var currentValue = parseInt($(this).val(), 10);
if (!isNaN(currentValue)) {
total += currentValue;
}
});
$(".total").val(total);
});
$('.add').click(function() {
$("<input type='text' class='price'>").appendTo($('.addition'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='addition'>
<input type="text" class="price">
<input type="text" class="price">
</div>
Total: <input type="text" class="total">
<button class='add'>Add</button>

关于javascript - 使用 jQuery 添加新输入字段时如何计算总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49746531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com