【问题标题】:Javascript: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'Javascript:无法在“节点”上执行“removeChild”:参数 1 不是“节点”类型
【发布时间】:2015-07-07 20:06:25
【问题描述】:

我正在尝试从其中一门课程中重新创建一些实践。它即将从 UL 中删除一个 li-item 并将其附加到另一个 UL。

当我以以下方式编写代码时,所有工作都可以找到

var removeMeandAppendMe = function() {
    var parentLi = this.parentNode;
    var goneElement = incompleList.removeChild(parentLi);
    compleList.appendChild(goneElement);
};

var li = incompleList.getElementsByTagName('li');

for (var i = 0; i < incompleList.children.length; i++) {
    var link = li[i];
    var liCheckArray = link.getElementsByTagName('input');
    var liCheck = liCheckArray[0];
    liCheck.onchange = removeMeandAppendMe;
}

当我将代码更改为以下代码时,我收到错误“无法在 'Node' 上执行 'removeChild':参数 1 不是 'Node' 类型”。

function removeMeandAppendMe(fromList, toList) {
    var parentLi = this.parentNode;
    var goneElement = fromList.removeChild(parentLi);
    toList.appendChild(goneElement);
}

var li = incompleList.getElementsByTagName('li');

for (var i = 0; i < incompleList.children.length; i++) {
    var link = li[i];
    var liCheckArray = link.getElementsByTagName('input');
    var liCheck = liCheckArray[0];
    liCheck.onchange = removeMeandAppendMe(incompleList, compleList);
}

困扰我的是,当我的 removeMeandAppendMe 函数不带参数且不带参数时,代码运行良好。谁能告诉我为什么以及我的错误在哪里?谢谢。

(我知道这里讨论的模糊问题:Failed to execute 'removeChild' on 'Node'

【问题讨论】:

  • 您可以创建一个fiddle 来显示您的问题吗?
  • 什么是incompleteList?分配在哪里?
  • incompleteListcompleList 是两个无序列表的id
  • 问题出在最后一行。您没有分配removeMeandAppendMe,而是在调用它。我建议查看 .bind() 函数来实现您想要做的事情。

标签: javascript removechild


【解决方案1】:

首先,正如 Pointy 所提到的,您确实需要将对 RemoveMeandAppendMe(incompleList, compleList) 的调用包装在一个匿名函数中,以免过早调用它。

考虑到这一点,您收到此错误是因为 this 的值是每个函数调用的情况。当调用RemoveMeandAppendMe()时,this是一个HTMLInputElement对象,但是当调用RemoveMeandAppendMe(incompleList, compleList)时,this是Window对象,所以this.parentNodeundefined(因此“不是'Node'类型”,这就是您看到该错误消息的原因)。

这个问题有很多微妙之处:this 指的是什么,以及如何处理不同的“函数”声明(大量讨论here)。仅仅改变RemoveMeandAppendMe(incompleList, compleList) 的声明方式也不能解决问题。

在某种程度上,您的问题归结为“为什么 this 引用 Window 对象进行参数化函数调用,而引用 HTMLInputElement 对象进行非参数化函数调用?”我相信在这种情况下,这是因为,当我们将参数化函数调用的调用包装在匿名函数中时(例如:liCheck.onchange = function(){removeMeandAppendMe(incompleList, compleList);};),removeMeandAppendMe 没有“本地”所有者,因此该函数的所有权默认为全局对象 Window (reference)。

要解决此问题,您可以将this 传递给removeMeandAppendMe 的调用,其中this 将引用复选框,然后将其用作该参数化函数中的变量。我已经把所有这些都放在你的fiddle 中,可以通过评论/取消评论不同的东西来玩东西。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 2021-02-19
    • 2015-01-20
    • 2023-04-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多