通过javascript添加列表项 [英] Add a list item through javascript

查看:175
本文介绍了通过javascript添加列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图打印出一个数组,可以添加用户输入文本,但是我想打印出来的是数组的有序列表。如你所见,(如果你运行我的代码)列表项,只是不断得到添加的用户输入,并且没有新的列表项添加人的名字。请帮忙!以下是以下代码:

So, I am trying to print out an array that gets user input text added to it, but what I want to print out is an ordered list of the array. As you can see, (if you run my code) the list item just keeps getting the user input added to it, and no new list items are added with people's names. Please help! Here is the code below:

 <!DOCTYPE html>
 <html>
 <head>
 First name: <input type="text" id="firstname"><br> 

 <script type="text/javascript">
 var x= [];

 function changeText2(){
var firstname = document.getElementById('firstname').value;
document.getElementById('boldStuff2').innerHTML = firstname;
x.push(firstname);
document.getElementById('demo').innerHTML = x;
 }
 </script>

 <p>Your first name is: <b id='boldStuff2'></b> </p> 
 <p> Other people's names: </p>

 <ol>
     <li id = "demo"> </li> 
 </ol>

 <input type='button' onclick='changeText2()'   value='Submit'/> 

 </head>
 <body>
 </body>
 </html>


推荐答案

如果您要创建一个 li 每个输入/名称的元素,那么你必须创建它,使用 document.createElement [MDN]

If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

给列表ID:

<ol id="demo"></ol>

并获得引用:

var list = document.getElementById('demo');

在事件处理程序中,创建一个新的列表元素,输入值作为内容并附加到列表中 Node.appendChild [MDN]

In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

var firstname = document.getElementById('firstname').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstname));
list.appendChild(entry);

演示

这篇关于通过javascript添加列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆