[英]creating list dynamically from the input of type text
In HTML i have input of type text and unordered list. 在HTML中,我输入了文本类型和无序列表。 when an enter is hit in the input, the text entered should be grabbed and added to the list.
当在输入中单击回车时,应抓取输入的文本并将其添加到列表中。 How can i achieve it using javascript without any library?
我如何在没有任何库的情况下使用javascript实现它?
The below code is what i've written but it not creating the list as expected. 下面的代码是我写的,但是没有按预期创建列表。 it is creating blank li and adding everything to the last li
它正在创建空白li并将所有内容添加到最后一个li
var newli = document.createElement("li"); var inp = document.getElementsByTagName("input"); var ul = document.getElementsByTagName("ul")[0]; inp[0].addEventListener("keypress", function(event){ if(event.which===13){ var inputText = this.value; this.value = " "; var node = document.createElement("LI"); newli.appendChild(document.createTextNode(inputText)); node.appendChild(newli); ul.appendChild( node ); } });
<input type="text"> <ul> <li>list 1</li> <li>list 2</li> <li>list 3</li> </ul>
You're appending newli
over and over again: 您要
newli
遍地添加newli
:
node.appendChild(newli);
So, on subsequent enter
s, it gets removed from its previous position in the DOM. 因此,在后续
enter
s上,它会从DOM中的先前位置删除。 Create a new LI inside the event handler instead: 而是在事件处理程序中创建一个新的LI:
const input = document.querySelector('input'); const ul = document.querySelector('ul'); input.addEventListener("keypress", function(event) { if (event.which === 13) { this.value = ""; const newli = document.createElement("li"); newli.textContent = this.value; ul.appendChild(newli); } });
<input type="text"> <ul> <li>list 1</li> <li>list 2</li> <li>list 3</li> </ul>
Your script needs to be as below. 您的脚本需要如下所示。 You need to comment some of your lines.
您需要注释一些行。 Read my comments just above the commented line for explanation.
阅读我在评论行上方的评论以进行解释。
You can see a full sample at: Running Sample 您可以在以下位置查看完整的示例: 运行示例
//no need of line below as a new li is being created in keypress event
//var newli = document.createElement("li");
var inp = document.getElementsByTagName("input");
var ul = document.getElementsByTagName("ul")[0];
inp[0].addEventListener("keypress", function(event){
if(event.which===13){
var inputText = this.value;
this.value = " ";
var node = document.createElement("LI");
node.appendChild(document.createTextNode(inputText));
//no need of line below as above line is already appending to new li some text
//node.appendChild(newli);
ul.appendChild( node );
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.