Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-Can';t使用replaceWith()函数-无法读取属性';createDocumentFragment';未定义的_Javascript_Jquery_Dom_Replace_Replacewith - Fatal编程技术网

Javascript jQuery-Can';t使用replaceWith()函数-无法读取属性';createDocumentFragment';未定义的

Javascript jQuery-Can';t使用replaceWith()函数-无法读取属性';createDocumentFragment';未定义的,javascript,jquery,dom,replace,replacewith,Javascript,Jquery,Dom,Replace,Replacewith,在与Axios通话后,我想用一个新项目替换当前项目。我这样说: var replacedElement=“”+ "" + ""; post(url).then(函数(响应){ $(this.replaceWith($.parseHTML(replacedElement)); }); 但我有以下错误:Uncaught(in promise)TypeError:无法读取未定义的属性“createDocumentFragment” My$(此)引用了span元素: 所以我不明白为什么我会有这个错误

在与Axios通话后,我想用一个新项目替换当前项目。我这样说:

var replacedElement=“”+
"" +
"";
post(url).then(函数(响应){
$(this.replaceWith($.parseHTML(replacedElement));
});
但我有以下错误:
Uncaught(in promise)TypeError:无法读取未定义的属性“createDocumentFragment”

My
$(此)
引用了
span
元素:


所以我不明白为什么我会有这个错误,这似乎是一个
这个
相关的错误,而不是jQuery错误。您可以检查如何在此基础上计算此

有三种简单的方法来解决你的问题

  • 存储在变量中(常用名称为
    self
  • 使用以确保此
    不会更改
  • 使用该选项不会改变
    参数
    (在较旧的浏览器中不起作用)

  • 您是否在
    then
    函数中添加了
    console.log(this)
    ,因为我很确定
    this
    不会引用相同的对象?如果这是问题所在,请尝试将
    this
    存储在变量中,如
    var self=this
    ,并在
    函数中使用
    self
    而不是
    this
    ,然后使用
    函数。您是对的。当我制作一个
    console.log($(this))
    时,我在调用axios之前就做了。干得好,谢谢!:)我添加了一个正确的答案,其中包含两个解决方案和一个链接,用于理解
    这个
    是如何计算的。
    var self = this;
    axios.post(url).then(function(response) {
      $(self).replaceWith($.parseHTML(replacedElement));
    });
    
    axios.post(url).then((function(response) {
      $(this).replaceWith($.parseHTML(replacedElement));
    }).bind(this));
    
    axios.post(url).then((response) => $(this).replaceWith($.parseHTML(replacedElement)));