我有这个功能用于添加/删除购物车中的东西(它在coffeescript中......但如果需要,我可以将其设为js):
$('.cart-link').bind('ajax:success', (evt, data, status, xhr) ->
current_link = $(this)
icon = $(current_link).find('i') //the cart icon
$(icon).toggleClass('icon-ico-addcart icon-ico-removecart') //if it was add, make it remove and vice versa
new_path = data['new_path']
$(current_link).attr('href', new_path)
if data['cart_size']
$('span.badge.cart-badge').text(data['cart_size'])
else
$('span.badge.cart-badge').text('')
大部分代码都有效。它会正确更改href
,它会更新徽章中的数字。唯一不起作用的是切换类,我无法弄清楚原因。如果我在控制台中运行这些命令,它就可以工作。我错过了什么?
我尝试创建一个单独的函数来查看它是否有一个类然后添加一个并删除旧类,但这也不起作用。
输出:
console.log current_link
console.log icon
是
[a.cart-link, context: a.cart-link]
0: a.cart-link
context: a.cart-link
length: 1
__proto__: jQuery[0]
[prevObject: jQuery.fn.init[1], context: a.cart-link, selector: "i"]
context: a.cart-link
length: 0
prevObject: jQuery.fn.init[1]
selector: "i"
__proto__: jQuery[0]
icon.length由于某种原因返回0?这是html:
<a class="cart-link" data-disable-with="" data-method="post" data-no-turbolink="true" data-remote="true" href="/en/cart/89/remove" rel="nofollow">
<img alt="pic" class="product" src="/assets/product1.png">
<i class="icon-ico-addcart icon"></i>
</a>
答案 0 :(得分:0)
导致我的问题的原因是数据字段中的disable_with
属性:
= link_to ... , data: { no_turbolink: true, disable_with: '' }, class: 'cart-link', method: :post, :remote => true do
...
这是一种很好的便利方法,但显然,它让所有孩子都无法选择。首先,我删除了该行:
= link_to ... , data: { no_turbolink: true}, class: 'cart-link', method: :post, :remote => true do
...
然后在我的coffee.js文件中:
//add this function to simulate the disabled link feature
$('.cart-link').click(->
current_link = $(this)
current_link.hide()
)
// after successful ajax, i need to show the link again.
$('.cart-link').bind('ajax:success', (evt, data, status, xhr) ->
current_link = $(this)
icon = $(current_link).find('i') //the cart icon
$(icon).toggleClass('icon-ico-addcart icon-ico-removecart') //if it was add, make it remove and vice versa
new_path = data['new_path']
$(current_link).attr('href', new_path)
if data['cart_size']
$('span.badge.cart-badge').text(data['cart_size'])
else
$('span.badge.cart-badge').text('')
// ADD THIS LINE
current_link.show()
这对我有用。