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

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

问题描述

因此,我试图打印出一个数组,该数组将用户输入的文本添加到其中,但我想打印的是该数组的有序列表.如您所见,(如果您运行我的代码)列表项只会不断地将用户输入添加到其中,并且不会添加带有人名的新列表项.

代码如下:

 <头>名字:
<script type="text/javascript">var x= [];函数 changeText2(){var firstname = document.getElementById('firstname').value;document.getElementById('boldStuff2').innerHTML = firstname;x.push(名字);document.getElementById('demo').innerHTML = x;}<p>你的名字是:<b id='boldStuff2'></b></p><p>其他人的姓名:</p><ol><li id = 演示"></ol><input type='button' onclick='changeText2()' value='Submit'/><身体>

解决方案

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

为列表提供 ID:

    并获得对它的引用:

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

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

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

    演示

    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.

    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>
    

    解决方案

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

    Give the list the ID:

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

    and get a reference to it:

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

    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);
    

    DEMO

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

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