繁体   English   中英

如何从输入框中添加新的数组元素并将其显示在列表中?

[英]How can I add new array element from input box and display it in list?

因此,我一直在尝试使js函数从输入字段中获取数据,然后将其添加到数组中,然后再将该数组显示为列表元素。 我的意思是,如果我有这样的列表:

然后在输入框中输入“三”,然后单击“添加”,将值添加到数组,并显示在类似

这是我的代码:

 function pushData(){ var i, n, slen,inputText,text; n = [""]; slen = n.length; inputText = document.getElementById('addNew').value; text="<ul>"; for(i=0;i<slen;i++){ text+="<li>"+inputText+"</li>"; } text+="</ul>"; n.push(inputText); document.getElementById('lists').innerHTML = text; } 
 body{ background: gray; } .liste ul{ list-style: none; padding: 0; } .liste ul li{ padding: 15px; background: #F5F5F5; color: gray; font-size: 20px; font-family: sans-serif; font-weight: 400; letter-spacing: 0.01cm; text-transform: uppercase; transition: 0.5s; } .liste ul li:hover{ font-size: 22px; cursor: pointer; color: black; } .liste ul li:nth-child(odd) { background: #DCDCDC; } 
 <input type="text" id="addNew" name="addNewList"> <button onclick="pushData()">Add</button> <div class="liste" id="lists"> </div> 

现在,当我在输入字段中输入新值时,列表中的值将被更改,而不会添加为新的列表元素。 谢谢。

你很近:D

我改变了什么:

  1. n是全局变量。
  2. 一次仅输出一个元素(无需每次都输出整个数组)。

 var n = []; function pushData(){ inputText = document.getElementById('addNew').value; n.push(inputText); // This does nothing, except keep an array internally. document.querySelector('#lists ul').innerHTML += "<li>" + inputText + "</li>"; } 
 body{ background: gray; } .liste ul{ list-style: none; padding: 0; } .liste ul li{ padding: 15px; background: #F5F5F5; color: gray; font-size: 20px; font-family: sans-serif; font-weight: 400; letter-spacing: 0.01cm; text-transform: uppercase; transition: 0.5s; } .liste ul li:hover{ font-size: 22px; cursor: pointer; color: black; } .liste ul li:nth-child(odd) { background: #DCDCDC; } 
 <input type="text" id="addNew" name="addNewList"> <button onclick="pushData()">Add</button> <div class="liste" id="lists"> <ul> </ul> </div> 

您需要在函数外部定义数组,因为每次调用该函数从输入文本中添加新值时,该数组都会初始化并且它会丢失之前累积的值。

 var n = []; function pushData(){ var i, slen,inputText,text; inputText = document.getElementById('addNew').value; n.push(inputText); slen = n.length; text="<ul>"; for(i=0;i<slen;i++){ text+="<li>"+ n[i] +"</li>"; } text+="</ul>"; document.getElementById('lists').innerHTML = text; } 
 body{ background: gray; } .liste ul{ list-style: none; padding: 0; } .liste ul li{ padding: 15px; background: #F5F5F5; color: gray; font-size: 20px; font-family: sans-serif; font-weight: 400; letter-spacing: 0.01cm; text-transform: uppercase; transition: 0.5s; } .liste ul li:hover{ font-size: 22px; cursor: pointer; color: black; } .liste ul li:nth-child(odd) { background: #DCDCDC; } 
 <input type="text" id="addNew" name="addNewList"> <button onclick="pushData()">Add</button> <div class="liste" id="lists"> </div> 

暂无
暂无

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

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