Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

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?

jsfiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 whatever 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 reference to the DOMElement you want to change in a variable that you can access in the callback.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...