【问题标题】:Access DOM element inside $.getJSON访问 $.getJSON 中的 DOM 元素
【发布时间】:2014-06-09 17:13:50
【问题描述】:

我正在开发一个应用程序,它迭代一些DOM 元素,并为每个元素执行Ajax 请求。问题是我无法访问回调函数中的每个 DOM 元素。

$('.class').each(function() {
    $.getJSON(url, function(data) {
        $(this).attr('id', data.id); // $(this) is not accessible
    });
});

有没有办法解决这个问题?

【问题讨论】:

    标签: javascript jquery dom getjson


    【解决方案1】:

    您应该使用一个变量,因为this 的值会随着每个函数调用而变化,并且在 $.getJSON 的回调中 this 不再是该元素。

    $('.class').each(function() { 
    
        var self = this;
    
        $.getJSON(url, function(data) {
            self.id = data.id;
        });
    });
    

    另一个选项是each() 中的内置参数

    $('.class').each(function(index, element) { 
        $.getJSON(url, function(data) {
            element.id = data.id;
        });
    });
    

    【讨论】:

    • 我不敢相信它这么简单,它甚至在异步模式下也能工作。非常感谢!
    【解决方案2】:

    您可以这样做而不必执行任务。

    $.getJSON(url, function(data) {
      $(this).attr('id', data.id); // $(this) is accessible
    }.call(this));
    

    演示:http://jsfiddle.net/8EWvC/4/

    【讨论】:

    • 非常感谢,但这个答案在 each 循环中不起作用。
    • 是的。看看链接。
    【解决方案3】:

    一种方法是使用Function#bind,如下所示:

    $('.class').each(function() {
        $.getJSON(url, function(data) {
            $(this).attr('id', data.id);
        }.bind(this)); // Pass `this` into the getJSON and now `this` should be the DOM element
    });
    

    它的作用是,无论您传递给bind,都将在函数内部设置为this。您可以通过阅读MDN here了解更多信息

    【讨论】:

    • 这个答案也很完美!再简单一点:) 非常感谢!
    【解决方案4】:

    您可以将选择器缓存在类似的变量中:

    $('.class').each(function() {
       var $this = $(this); // cache it here
       $.getJSON(url, function(data) {
          $this.attr('id', data.id); // $(this) is not accessible
       });
    });
    

    或者,如果您能够将 $.getJson() 更改为传统的 $.ajax(),那么您可以使用 context:this, 参数:

    $('.class').each(function() {
       $.ajax({
          url : url, 
          dataType: 'json',
          context: this,
          success: function(data) {
              this.id = data.id; // $(this) is not accessible
          }
       });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2014-03-18
      • 2021-09-05
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      相关资源
      最近更新 更多