简体   繁体   English

几乎相同的代码,不同的输出。 什么是JavaScript在这里做的不同?

[英]Almost same code, different output. What is JavaScript doing differently here?

First Code! 第一码!

 x = 6; document.getElementById("btn").addEventListener("click", function() { var list = document.createElement("li"); var apple = document.getElementById("our-list"); list.appendChild(document.createTextNode("Something " + x++)); apple.appendChild(list); }); 
 <body> <button id="btn">Click</button> <ul id="our-list"> <li>Something 1</li> <li>Something 2</li> <li>Something 3</li> <li>Something 4</li> <li>Something 5</li> </ul> <script src="./javascript.js"></script> </body> 

Test Code! 测试代码! (Yes, I know it looks disgusting but its only for understanding and testing purpose.) (是的,我知道它看起来很恶心,但它仅用于理解和测试目的。)

 var x = 6; document.getElementById("btn").addEventListener("click", function() { document.getElementById("our-list").appendChild(document.createElement("li").appendChild(document.createTextNode("Something " + x++))); }); 
 <body> <button id="btn">Click</button> <ul id="our-list"> <li>Something 1</li> <li>Something 2</li> <li>Something 3</li> <li>Something 4</li> <li>Something 5</li> </ul> <script src="./javascript.js"></script> </body> 

Why is this not creating a list element? 为什么这不是创建列表元素? It seems like its entirely skipping the document.createElement("li") and appending a TextNode straight away! 它似乎完全跳过document.createElement("li")并直接追加TextNode!

Because, in your second code, you are appending the return value of 因为,在第二个代码中,您要附加返回值

document.createElement("li").appendChild(document.createTextNode("Something " + x++))

to the document.getElementById("our-list") . document.getElementById("our-list")

If you look at the documentation of appendChild , this method returns the appended child node. 如果查看appendChild文档 ,此方法将返回附加的子节点。 Therefore, when you do 因此,当你这样做

document.createElement("li")
.appendChild(document.createTextNode("Something " + x++))

what you are appending to the our-list is not the newly created li element, but the child note which you intended to be inside that li node. 你附加到我们列表的内容不是新创建的li元素,而是你想要在li节点内的子注释。

You can use the below code to do the same in one line without using variables. 您可以使用以下代码在一行中执行相同操作而不使用变量。 Hope this will help you. 希望这会帮助你。

document.getElementById("our-list").appendChild(document.createElement("li")).appendChild(document.createTextNode("Something " + x++));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM