[英]i think that the code is the same but i don't know why it make different results
Why does the code make difference output and it is almost the same input?为什么代码有所不同 output 并且几乎是相同的输入? Input:
输入:
var Add = document.getElementById('AddElement'); //the button
var Element = document.getElementById('element'); // the input text
var ListParent = document.querySelector('ul');
Add.addEventListener('click', function(){
var AddText = document.createElement('li').appendChild(document.createTextNode("hello"));
ListParent.appendChild(AddText);
})
Output: Output:
first click: hello第一次点击:你好
second click: hellohello第二次点击:你好你好
Input:
var Add = document.getElementById('AddElement');
var Element = document.getElementById('element');
var ListParent = document.querySelector('ul');
Add.addEventListener('click', function(){
var AddText = document.createElement('li');
AddText.appendChild(document.createTextNode('hello'));
ListParent.appendChild(AddText);
})
Output: first click: Output:首先点击:
second click:第二次点击:
appendChild
returns the appended node: appendChild
返回附加的节点:
const div = document.createElement('div'); const parent = document.createElement('div'); const result = parent.appendChild(div); console.log(result === div);
So when you do所以当你这样做时
var AddText=document.createElement('li').appendChild(document.createTextNode("hello"));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The value put into addText
is the created text node.放入
addText
的值是创建的文本节点。 In contrast, with与...相比
var AddText = document.createElement('li');
it's the <li>
, not the text node.它是
<li>
,而不是文本节点。
So, with the first approach, the created <li>
doesn't get used (and probably isn't what you want).因此,使用第一种方法,创建的
<li>
不会被使用(并且可能不是您想要的)。
If you wanted to use the <li>
, and slim your code down, assign to the .textContent
of the <li>
instead.如果您想使用
<li>
并精简代码,请改为分配给<li>
的.textContent
。
Add.addEventListener('click', function(){
ListParent.appendChild(document.createElement('li'))
.textContent = element.value;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.