未捕获的TypeError:无法读取未定义的属性"createDocumentFragment"

use*_*629 54 javascript jquery twitter-bootstrap

我试图抓住一个网页并加载到一个bootstrap 2.3.2 popover.到目前为止,我有:

$.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");
Run Code Online (Sandbox Code Playgroud)

当我激活此代码时,我收到错误:

未捕获的TypeError:无法读取未定义的属性"createDocumentFragment"

这是什么问题,我该如何解决?

jsfiddle

t.n*_*ese 81

错误的原因是$(this).html($link); 你的.done()回调.

this在回调中指的是([...]object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax)[...]而不是你想要的$(".btn.btn-navbar")它应该引用的任何东西).

所引发的错误,因为jQuery将内部调用.createDocumentFragment()ownerDocument传递与对象的this,当你执行$(this).html($link);,但在你的代码this是不是一个DOMElement,并没有一个ownerDocument.因为那ownerDocument是因为这就是undefined为什么createDocumentFragment被召唤的原因undefined.

您需要使用context 您的ajax请求选项.或者,您需要在 要在回调中访问的变量中保存要更改的DOMElement 的引用.

  • 尽管这可能是一个很好的答案,但它并没有解释神秘的"_annot read属性'createDocumentFragment'的undefined_"错误. (2认同)
  • @davidkonrad编辑了添加此信息的答案 (2认同)
  • @ user61629你只需要将`context:theElementYouWant,`添加到你的`$ .ajax()`选项中(更多细节你应该查看[jQuery.ajax]的文档(https://api.jquery.com /jquery.ajax/)我已经链接了)然后回调中的`this`将引用`theElementYouWant`.我不能做一个例子,因为我不知道`this`应该是什么元素;) (2认同)

小智 10

发生该错误this是因为引用了ajax对象而不是DOM元素,为了解决这个问题,你可以这样做:

$('form').on('submit', function(){
    var thisForm = this;

    $.ajax({
        url: 'www.example.com',
        data: {}
    }).done(function(result){
        var _html = '<p class="message">' + result + '</p>';
        $(thisForm).find('#resultDiv').html(_html);
    });
});
Run Code Online (Sandbox Code Playgroud)