【问题标题】:Unable to Toggle a Class in jquery无法在 jquery 中切换类
【发布时间】:2015-07-29 02:31:29
【问题描述】:

我有这个功能可以在购物车中添加/删除东西(它在咖啡脚本中......但如果需要我可以将其设为 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>

【问题讨论】:

  • 不确定,但试试ajaxSuccess
  • 我想我可以尝试一下,但就像我说的,代码块中的所有内容都在触发,除了那一行。
  • 我不认为这是问题所在,但没有必要在那里重新包装icon$().find() 已经返回一个 jQuery 集合。对于调试,我会尝试console.log(icon.length) 以确保您确实找到了一些东西。
  • 如果您不确定,为什么要标记为重复?它与那个问题无关。
  • @Tushar 这个问题与您引用的问题不重复。

标签: jquery ajax coffeescript


【解决方案1】:

导致我出现问题的原因是数据字段中的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()

这对我有用。

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2014-05-05
    • 2012-08-30
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    相关资源
    最近更新 更多