新手问题 jQuery 绑定对象在 Ajax 之后不能更新怎么办?

messiahxu · 2013年08月08日 · 最后由 nouse 回复于 2013年08月09日 · 4027 次阅读

最近在做的一个小应用,因为要实现多个页面中的关注和取消关注功能,用 ujs 的话就会很难搞,在参考了 @Rei 的文章之后,改用客户端 Ajax 来做,果然很方便,不过现在有一个问题,就是 jQuery 绑定的事件在 ajax 发送完成之后不会更新,导致关注或者取消关注的按钮只能点一次,再点的话,就会报错。

只能跪求指点了。

相关的 JS 代码是下面这部分:

$(document).ready ->
  $(".follow").on "click", ->
    user_id = $(this).attr("data-user-id")
    _this = $(this)
    $.ajax
      type: "POST"
      url: "/relationships"
      dataType: "json"
      data:
        user_id: user_id
      success: (data) ->
        _this.text("取消关注").attr("data-relationship-id", data["relationship-id"]).removeClass("follow").addClass("unfollow")


  $(".unfollow").on "click", ->
    user_id = $(this).attr("data-user-id")
    _relationship_id = $(this).attr("data-relationship-id")
    _this = $(this)
    $.ajax
      type: "POST"
      url: "/relationships/" + _relationship_id
      dataType: "json"
      data:
        user_id: user_id
        _method: "delete"
      success: ->
        _this.text("关注").removeAttr("data-relationship-id").removeClass("unfollow").addClass("follow")

1 楼 已删除

既然用到了 data-,不如就用.data() 来操作吧。 http://api.jquery.com/data/

要绑到父级元素

$('.user').on 'click', '.follow', ->
  ...

$('.user').on 'click', '.unfollow', ->
  ...

#3 楼 @Rei 果然要这样,被自己蠢哭了……

#4 楼 @miclle 我的是在用户列表里,用 ujs 实在是不好做

#6 楼 @messiahxu 我就在用户列表里面也做过,还好

#7 楼 @miclle 感觉会很麻烦……有例子可以参考一下吗

#8 楼 @messiahxu http://ruby-china.org/topics/12306#3 楼 是单个的,如果放在列表中 link 的 :id => "follow-action-#{user.id}",erb 中相应改下

#9 楼 @miclle 可 js.erb 中怎么写?难道可以 $("#follow-action-#{user.id}") 这样?

#10 楼 @messiahxu $("#follow-action-<%= @user.id -%>")

#11 楼 @miclle 原来还可以这么用啊,长姿势了

#1 楼 @miclle 为什么呢?on 的出现不是为了统一事件绑定的 API 么,以前有 live,delegate,bind,现在用 on 就行了

#13 楼 @loveky 哦,我理解错了

用 on 可以,但要绑定到父级元素才行。

你的各种 _this = $(this) 写法 success: -> 写成 success: => 就会把外面的 this 带进里面的 this

我建议楼主把 CodeSchool 的两部 jQuery 视频过一遍,以后再也不用发愁 jQuery 的问题了,讲得非常好。

#16 楼 @zj0713001 其实我是先用 js 写好,再转成 coffee 的……

#18 楼 @messiahxu ..........这..........

#18 楼 @messiahxu 这 ... 写好 js , 然后转换成 coffee , coffee 再转换成 js ..... 这 ....

其实就是一个事件委托的问题,动态元素的事件绑定要移到父元素来处理就行

曾经的 live 方法,现在的 on 方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号