javascript - click 事件不会在 ajax 加载的对象上触发
问题描述
我正在使用 ajax 填充我的购物车。在购物车中,我有一个带有加号和减号按钮的数量字段。这是按钮的代码:
<div class="cart-quantity">
<input type='button' value='+' class='qtyplus CartCount' field='updates_{{ item.id }}' />
<input name="updates[]" id="updates_{{ item.id }}" class="quantity CartCount" value="{{ item.quantity }}" />
<input type='button' value='-' class='qtyminus CartCount' field='updates_{{ item.id }}' />
</div>
这是通过加号/减号按钮更新数量字段的javascript:
// This button will increment the value
$('.qtyplus').on("click", function(){
// Stop acting like a button
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[id='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
e.preventDefault();
$(this).closest('form').submit();
});
// This button will decrement the value till 0
$(".qtyminus").on("click",function() {
// Stop acting like a button
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
e.preventDefault();
$(this).closest('form').submit();
});
如您所见,我已尝试将单击事件更改为单击,但仍然无法正常工作。有任何想法吗?
解决方案
与其直接将click
事件绑定到.qtyplus
,不如尝试:
$(document).on('click', '.qtyplus', function() { /* ... */ });
为了获得更好的性能,不要将其绑定到 ,而是document
使用最接近的.qtyplus
元素父级。
推荐阅读
- php - 无效的日期时间格式:1292 使用旧日期时
- c++ - C++ 中带有编译时检查的链表
- apache - “xampp”服务器在安装后未在 Windows 10 中打开
- mysql - 你如何在M2中按类别ID查询所有库存产品?
- mysql - MySQL 中 SQL 脚本的默认数据库
- mysql - 如何在不更改其中数据的情况下将表的模式从一个数据库导入到另一个数据库中的现有表?
- javascript - 删除/过期 cookie 在 Windows 7 和 Windows 10 的 IE11 中的工作方式不同
- javascript - 数据表显示错误但显示数据不正确
- rest - Jax rs - 具有空值的 PATCH 方法行为
- java - 删除/替换字符串值的一部分