未捕获的类型错误:无法读取 null javascript 的属性“parentNode”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18407390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:48:23  来源:igfitidea点击:

Uncaught TypeError: Cannot read property 'parentNode' of null javascript

javascript

提问by Kepedizer

This code should make an element disappear from a list when it is dropped on another element (called cookiemonster)

当一个元素被放到另一个元素(称为 cookiemonster)上时,此代码应该使该元素从列表中消失

addEvent(cookiemonster, 'drop', function (e) {
  if (e.stopPropagation) e.stopPropagation();

  var el = document.getElementById(e.dataTransfer.getData('text'));
  el.parentNode.removeChild(el);
  return false;
});

采纳答案by eventHandler

create an auxiliar variable like this

创建一个像这样的辅助变量

addEvent(cookiemonster, 'drop', function (e) {
    if (e.stopPropagation) e.stopPropagation();

    var el = document.getElementById(e.dataTransfer.getData('text'));
    var aux = el.parentNode;
    aux.removeChild(el);
    return false;
});