繁体   English   中英

Ajax调用后在模板中找不到元素

[英]Can't find element in my template after ajax call

我正在尝试在Ajax调用成功的情况下在模板中找到图像...但是我不能!

这是我的代码:

class AvatarView extends Backbone.View
  template: JST["backbone/templates/twitter_avatar"]

  initialize:(options) ->
    @user = options.user

  render: =>
    @$el.html(@template({
      view_id: @cid
      avatar_url: @user.avatar() || "src/image_not_found.png"
    }))
    @$el.find(".avatar").on('error', @_reloadAvatar)

  _reloadAvatar: =>
    $.ajax
      type: 'GET'
      url: "/profiles/api/twitter/#{@user.social_network_id()}/avatar_url"
      success: (response) =>
        if response.success
          avatar_url = response.avatar_url
        else
          avatar_url = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_0_normal.png'
        @$el.find(".avatar").attr('src', avatar_url)  # Here is the problem 

当我调试此:

  • “这”是AvatarView的实例,
  • @ $ el是一个空div,无法找到头像类。

这是模板:

<img src="<%= avatar_url %>" alt="avatar" class="avatar" id="avatar-image-<%= view_id %>">

我跌倒了,就像失去了DOM对象之类。

我仍然不明白为什么它不起作用,但是我使用事件参数解决了我的问题:

_reloadAvatar:(event) =>
$.ajax
  type: 'GET'
  url: "/profiles/api/twitter/#{@user.social_network_id()}/avatar_url"
  success: (response) =>
    if response.success
      avatar_url = response.avatar_url
    else
      avatar_url = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_0_normal.png'
    @(event.target).attr('src', avatar_url)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM