javascript 为什么在 Div 中重复添加新元素时会出现“HierarchyRequestError”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21937549/
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 22:02:49  来源:igfitidea点击:

Why do I get a `HierarchyRequestError` when I repeat adding a new element Inside a Div?

javascripthtml

提问by Ed Pudol

Consider the code below. It works the first time, but not on following presses of the button. I am getting the following error message:

考虑下面的代码。它第一次工作,但不是在按下按钮后。我收到以下错误消息:

Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.

未捕获的 HierarchyRequestError:无法在“节点”上执行“appendChild”:新的子元素包含父元素。

function addElement() {
var txt='<input type="text" name="school[]"> '+
    '<input type="text" name="degree[]">'+
    '<input type="text" name="gradYear[]">';

    var ni = document.getElementById('school');
    ni.innerHTML = txt;
    ni.appendChild(ni);
}


<input type="button" name="add" value="Add School" onClick="addElement()">

<div id="school">

</div>

回答by StephenRios

You are trying to append an element inside itself. JavaScript won't let you do that.

您正试图在其内部附加一个元素。JavaScript 不会让你这样做。

回答by Suman Bogati

This is wrong ni.appendChild(ni);, you can not do the self append. You can append the tag inside it's parent. Here how we can append the input tag inside it's parent.

这是错误的 ni.appendChild(ni);,您不能进行自我追加。您可以将标签附加到其父级中。这里我们如何将输入标签附加到它的父标签中。

function addElement() {
    var ni = document.getElementById('school');

    var firstInput = createInput('school');
    ni.appendChild(firstInput);

    var seconInput = createInput('degree');
    ni.appendChild(seconInput);

    var thirdInput = createInput('gradYear');
    ni.appendChild(thirdInput);
}

function createInput(name){
    var input = document.createElement('input'); // creating the input
    input.setAttribute('type', 'text'); // setting the type attribute
    input.setAttribute('name', name+'[]');
    return input;
}

The working DEMO

工作 演示

回答by jgitter

You can either set the innerHTML, or you can use ni.appendChild() to add HTML DOM Nodes. Choose one or the other, not both.

您可以设置innerHTML,也可以使用ni.appendChild() 添加HTML DOM 节点。选择其中之一,而不是两者。

The error is because you tried to do ni.appendChild(ni), for which the message should be obvious.

错误是因为您尝试执行 ni.appendChild(ni),因此消息应该很明显。