导航菜单
路很长,又很短
博主信息
昵   称:Cocodroid ->关于我
Q     Q:2531075716
博文数:290
阅读量:550372
访问量:51388
至今:
×
云标签 标签球>>
云标签 - Su的技术博客
博文->>首页 博主的更多博文>>
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
Tags : JQuery发表时间: 2015-10-10 20:12:45
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。
比如: 转自:Su的技术博客  原文地址:

请看例子,也是我遇到的:)

问题:

I am trying to grab a webpage and load into a bootstrap 2.3.2 popover. So far I have:

$.ajax({
  type: "POST",
  url: "AjaxUpdate/getHtml",
  data: {
    u: 'http://stackoverflow.com'
  },
  dataType: 'html',
  error: function(jqXHR, textStatus, errorThrown) {
    console.log('error');
    console.log(jqXHR, textStatus, errorThrown);
  }
}).done(function(html) {
    console.log(' here is the html ' + html);

    $link = $('<a href="myreference.html" data-html="true" data-bind="popover"' 
            + ' data-content="' + html + '">');
    console.log('$link', $link);
    $(this).html($link);

    // Trigger the popover to open
    $link = $(this).find('a');
    $link.popover("show"); 

When I activate this code I get the error:

Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

What is the problem here and how can I fix it?

回答:

The reason for the error is the $(this).html($link); in your .done() callback.

this in the callback refers to the [...]object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax)[...] and not to the $(".btn.btn-navbar") (Or what ever you expect where it should refer to).

The error is thrown because jQuery will internally call .createDocumentFragment() on the ownerDocument of object you pass with this when you execute $(this).html($link); but in your code the this is not a DOMElement, and does not have a ownerDocument. Because of that ownerDocument is undefined and thats the reason why createDocumentFragment is called on undefined.

You either need to use the context option for your ajax request. Or you need to save a referenceto the DOMElement you want to change in a variable that you can access in the callback.


相信你能很好的看懂,由于我英文不怎么样。所以我只说解决方法。:)

    在异步请求之前你要根据点击获取事件对象时,需要保存this,之后你回调后才能使用this不然就会出现那个问题,这也是JQuery的处理方式所决定的。

    即:var t = $(this);

    之后随便使用t来代替$(this)即可。



参考:http://stackoverflow.com/questions/28177917/uncaught-typeerror-cannot-read-property-createdocumentfragment-of-undefined






打赏
打赏
关注公众号
公众号
类别:Web前端| 阅读(1966)| 赞 (1)
评论
暂无评论!
发表评论
昵  称:

验证码:

内  容:

    同时赞一个 赞