This question already has answers here:
Event binding on dynamically created elements?
(23个答案)
2年前关闭。
我正在使用ajax填充购物车。在购物车中,我有一个带有加号和减号按钮的数量字段。
这是按钮的代码:
这是通过加/减按钮更新数量字段的javascript:
如您所见,我已经尝试将click事件更改为on click,但是它仍然无法正常工作。有任何想法吗?
为了获得更好的性能,而不是将其绑定到
(23个答案)
2年前关闭。
我正在使用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事件更改为on click,但是它仍然无法正常工作。有任何想法吗?
最佳答案
代替直接将click
事件绑定到.qtyplus
,请尝试:
$(document).on('click', '.qtyplus', function() { /* ... */ });
为了获得更好的性能,而不是将其绑定到
document
,请使用最接近的.qtyplus
元素父级。