【问题标题】:jQuery - Can't use replaceWith() function - Cannot read property 'createDocumentFragment' of undefinedjQuery - 无法使用 replaceWith() 函数 - 无法读取未定义的属性“createDocumentFragment”
【发布时间】:2021-04-01 05:45:43
【问题描述】:

与 Axios 通话后,我想用新的项目替换当前项目。我是这样进行的:

var replacedElement = "<span class='float-right' aria-hidden='true'>" +
            "<i class='fas fa-check icon-color'></i>" +
            "</span>";

        axios.post(url).then(function (response) {
           $(this).replaceWith($.parseHTML(replacedElement));
        });

但我有以下错误:Uncaught (in promise) TypeError: Cannot read property 'createDocumentFragment' of undefined

我的$(this) 引用了span 元素:

所以我不明白为什么会出现这个错误

【问题讨论】:

  • 您是否在then 函数中添加了console.log(this),因为我很确定this 不会引用同一个对象?如果这是问题,请尝试将this 存储在var self = this 之类的变量中,并在then 函数中使用self 而不是this
  • 你是对的。我做console.log ($(this))的时候,是在调用axios之前做的。做得好,谢谢! :)
  • 我添加了一个正确的答案,其中包含几个解决方案和一个链接,用于了解如何计算 this

标签: javascript jquery dom replace replacewith


【解决方案1】:

这似乎是与this 相关的错误,而不是 jQuery 错误。你可以查看this 是如何在这个other answer I've posted 上计算出来的。

有 3 种简单的方法可以解决您的问题。

  1. this 存储在变量中(通用名称为self
var self = this;
axios.post(url).then(function(response) {
  $(self).replaceWith($.parseHTML(replacedElement));
});
  1. 使用Function#bind 确保this 不会改变
axios.post(url).then((function(response) {
  $(this).replaceWith($.parseHTML(replacedElement));
}).bind(this));
  1. 使用Arrow Functions 不会改变argumentsthis(在旧版浏览器中不起作用)
axios.post(url).then((response) => $(this).replaceWith($.parseHTML(replacedElement)));

【讨论】:

    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 2015-03-26
    • 2021-11-26
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多