【问题标题】:"Cannot read property 'createDocumentFragment' of undefined"“无法读取未定义的属性‘createDocumentFragment’”
【发布时间】:2018-05-06 17:18:09
【问题描述】:
$(document).ready(function(){
    $(".item-title a").each(function(index) { 
        var yaz = $(this).attr("href");
        $.ajax({
            url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath=='+yaz+'&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
            type: 'get',
            dataType: "jsonp",
            success: function(data){  
                $(this).append(data.rows);
            }
        });
    });
});

控制台:未捕获类型错误:无法读取未定义的属性“createDocumentFragment”

什么问题?
请帮忙。

【问题讨论】:

  • 如果这很重要,不要担心,但你的意思是让pagePath== 有两个等于?
  • @Intervalia 这是 metrica url 参数

标签: javascript jquery this each


【解决方案1】:

这是因为 success 回调中的 this 上下文。 它没有像您期望的那样指向回调内的jQuery 对象。它将引用当前上下文。

success: function(data){  
    $(this).append(data.rows);;
}

this 的上下文保存在success 之外并重复使用。

var cachedThis = this;

$.ajax({
   ...
   success: function(data){  
      $(cachedThis).append(data.rows);;
   }
   ...
});

相反,您可以使用bind 方法来锁定上下文。

$.ajax({
   ...
   success: function(data){  
       $(this).append(data.rows);;
   }.bind(this)
   ...
});

【讨论】:

  • 打败我!!他也可以把变量 yaz 放在那里 $(yaz).append(data.rows);
猜你喜欢
  • 2021-04-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2020-10-30
  • 2019-10-09
  • 1970-01-01
相关资源
最近更新 更多