jquery - jQuery "this" apparently not selecting unique instance
问题描述
I'm trying to understand why clicking on the "Price" input only works on the first instance. If I add other instances, they don't produce the value. That seems like a good description of the problem, but I am prompted to write more!
$('#add-line').click(function() {
var lastItem = $(this).prev();
var lastItemNumber = lastItem.attr("data-income-line");
var nextItemNumber = parseInt(lastItemNumber) + 1;
lastItem.clone().attr('data-income-line', nextItemNumber).insertAfter(lastItem);
});
// addition
$('.total').click(function () {
var line = $(this).parent().parent();
var price = line.find("input[name='price']").val();
var quantity = line.find("input[name='quantity']").val();
var total = parseInt(price) * parseInt(quantity);
line.find("input[name='total']").val(total);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="income-line" data-income-line="1">
<div class="item-wrapper income-name">
name<input type="text" name="item_name" />
</div>
<div class="item-wrapper income-price">
price<input type="text" name="price" />
</div>
<div class="item-wrapper income-x">
X
</div>
<div class="item-wrapper income-quantity">
quantity<input type="text" name="quantity" class="quantity" />
</div>
<div class="item-wrapper income-total">
total<input type="text" name="total" class="total"/>
</div>
<div style="clear:left"></div>
</div>
<div id="add-line" class="add-line">
add
</div>
解决方案
The problem is that the click handler is only created for the first .total
. For elements that are created at a later time, you should rely on event delegation. Use on
:
$(document).on('click', '.total', function () {
// ...etc
})
推荐阅读
- javascript - 从 Angular 指令绑定子元素值
- python - .iloc[] 中可调用的 Lambda 函数
- c++ - 您可以像删除普通整数一样删除 1 个整数的 C 数组吗?
- cucumber - Courgette-jvm 在报告中包含项目名称、版本和环境?
- linux - 尝试连接到关闭的端口时,getsockopt 不返回错误
- ios - 有什么方法可以将视图从 swiftUI 更改为 UIKit?
- java - 如何正确显示用户的个人资料图片
- bash - 使用 getopt 解析负值的参数 - 有什么方法可以让 getopt 忽略它们?
- php - 我在循环内的查询处理时间过长
- java - 在 Spring boot 和 Angular App 的 Tomcat 上部署 WAR 文件