Javascript jQuery-Can';t使用replaceWith()函数-无法读取属性';createDocumentFragment';未定义的
在与Axios通话后,我想用一个新项目替换当前项目。我这样说: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元素: 所以我不明白为什么我会有这个错误
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)));