【问题标题】:Cannot use $(this) in $.getJSON in .each不能在 .each 中的 $.getJSON 中使用 $(this)
【发布时间】:2016-01-16 10:28:09
【问题描述】:

我正在构建自定义 Minecraft 服务器状态并遇到问题。第一个版本是成功的,但代码相当长,我决定让它变得更好更短。该脚本应该填充每个 .server 的元素,但它不起作用。

<div class="server_status">
  <div class="container servers_info">
    <h1>My Network</h1>
    <div id="of the server" class="server" title="of the server" server-ip="0.0.0.0">
        <div class="name"></div>
        <div class="count"><i class="fa fa-spinner fa-spin"></i></div>
        <div class="players">Loading player data <i class="fa fa-spinner fa-spin"></i></div>
        <div class="status"></div>
    </div>
    <div id="of the server" class="server" title="of the server" server-ip="0.0.0.0">
        <div class="name"></div>
        <div class="count"><i class="fa fa-spinner fa-spin"></i></div>
        <div class="players">Loading player data <i class="fa fa-spinner fa-spin"></i></div>
        <div class="status"></div>
    </div>
    <!-- ..... more servers -->
  <span class="total"><i class="fa fa-spinner fa-spin"></i></span>
</div>

$(document).ready(function ping() {
  $( ".servers_info .server" ).each( function() {
    var name = $(this).attr( "title" );
    var ip = $(this).attr( "server-ip" );
    var id = $(this).attr( "id" );
    var total = 0;
    var call = "Get Avatar List adress";

//Set the name:    
    $(".name",this).html(name);          
//Gets the data:      
    $.getJSON("http://mcapi.ca/v2/query/info/?ip=" + ip, function (json) {
//Checks The status and applies visual effects:    
        if (json.status !== "false") {
            $(".status",this).html("<span class=\"l-online\">" + json.ping + " ms</span>");
            $(this).removeClass('blur');
        } else { 
            $(".status",this).html("<span class=\"l-offline\">0 ms</span>");
            $(this).addClass('blur');
        };
     });
  });
  //Sets Refresh rate of 10s
  setTimeout(ping, 10000);
});

我将问题缩小到$.getJSON 部分。数据被正确检索,但不能放置在其各自的 DIV 中。与脚本的第一个版本的唯一区别是我为每个要显示的服务器分别使用了 4 个getJSON。现在使用 .each 将其组合为所有 4 个,并使用 $(this) 来使用相关对象。

我怀疑问题出在 .get 中 $(this) 的使用中,但我不确定也不知道如何解决。

【问题讨论】:

    标签: this each getjson


    【解决方案1】:

    正如您所怀疑的,问题在于 $(this)。部分。在$.getJSON 回调内部this 不再引用触发事件的DOM 对象。

    要解决此问题,您可以:

    在回调函数中添加.bind(this)。函数本身不需要更改。

    $.getJSON(url, function(json) {
      /* all your code here */
      }.bind(this)
    );
    

    或者在$.getJSON之前保存对this的引用并在回调中使用它。

    var _this = this;
    $.getJSON(url, function(json) {
       /* replace all references of this to _this for example*/
       $(_this).removeClass('blur');
    
    });
    

    希望有帮助

    【讨论】:

    • 感谢您的回复。我几分钟前通过使用 $(this) 创建另一个变量解决了这个问题
    猜你喜欢
    • 2012-03-16
    • 2014-08-09
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2011-12-02
    • 2012-05-22
    相关资源
    最近更新 更多