javascript - 单击事件不会在 ajax 加载的对象上触发

标签 javascript jquery

我正在使用 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 事件绑定(bind)到 .qtyplus,而是尝试使用:

$(document).on('click', '.qtyplus', function() { /* ... */ });

为了获得更好的性能,不要将其绑定(bind)到 document,而是使用最接近的 .qtyplus 元素父元素。

关于javascript - 单击事件不会在 ajax 加载的对象上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51769517/

相关文章:

javascript - 如何在 ASP.NET ViewState HiddenField 中设置 ASP.NET TextBox 值

javascript - 在另一个 AJAX 调用之前重用 JavaScript AJAX 调用

javascript - Cufon 鼠标悬停

javascript - 解析带有子元素的 json 对象出错

javascript - 使用 jQuery Tokeninput 时如何使匹配字符变为粗体+红色

jquery - 如果我从数据库获取文本,如何更改 jQuery Ui 自动完成功能以获取 id?

jQuery UI 可排序排序动态添加的新 ul

javascript - 如何获取 masonry 和图像以与Wordpress一起使用

javascript - Node.js:注册 token 不是有效的 FCM 注册 token

php - 解析位置41时间字符串失败(i) : Double timezone specification