在下一个div上选择一个类

时间:2016-12-13 17:56:28

标签: jquery

以下是我想要选择的范围product_qty,但我的代码不起作用。

<div class="pull-left">
    <div class="update-product">
       <a title="Plus This" href="#" onclick="addtoCart(531,530 ,1)"><i class="fa fa-plus-circle"></i></a>
    </div>
</div>

<span class="pull-left">
   <span class="product_qty"></span>
</span>

我点击update-product div中的锚点按钮。该功能用作AJAX,然后我想选择product_qty并更新其HTML。我试过这个:

$(this).closest('.pull-left').next().find('.product_qty').html(data.quantity);

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

你在AJAX调用的成功回调函数中调用$(this).closest('.pull-left')..,这意味着this并不是指你的想法(即锚标记)。该函数在被调用时将具有不同的“上下文”。

你可以:

  • 明确地参考您的范围:例如$('.pull-left .product_qty')
  • 正如一些人已在评论中提到的那样,您可以在启动AJAX调用之前定义并分配变量,并存储对该锚标记的引用。以下示例

如果你正在使用onclick属性,那么你可以将元素传递给函数:

<a onclick="removeFromCart(this, 'ABCDEFXYZ', 123, 1)">Remove</a>

function removeFromCart(elem, hash, r_id, qty) {
    var anchor = $(elem);
    ... 
}

或者如果您与jQuery绑定

会更容易

$('a.remove').on('click', removeFromCart)并且您不需要函数定义中的elem参数