首页 > 解决方案 > 当用户在输入字段中输入以逗号分隔的值时。如何以列表格式显示输出

问题描述

在此输入字段中。当用户输入一个以逗号分隔的值时。例如像“苹果、香蕉、葡萄、芒果”。因此,如果用户以这种格式输入值。然后我想以列表格式显示输出,例如

apple
Banana
grapes
mango

因此,如果可以做到,请告诉我们如何做到这一点。下面是我尝试过的代码

<input type='text' id='idea' />
<input type='button' value='add to list' id='add' />
<ul id='list'></ul>
<script>
document.getElementById("add").onclick = function() {
    //First things first, we need our text:
    var text = document.getElementById("idea").value; //.value gets input values

    //Now construct a quick list element
    var li = "<li>" + text + "</li>";

    //Now use appendChild and add it to the list!
    document.getElementById("list").appendChild(li);
}
</script>

标签: html

解决方案


你快到了,但你不能在字符串中附加 HTML,你需要创建正确的列表项对象并附加这些:

document.getElementById("add").onclick = function() {
  // cache the list
  const list = document.getElementById("list");
  
  //First things first, we need our text:
  const items = document.getElementById("idea").value.split(','); //.value gets input values, .split(',') makes it an array of values
  
  // foreach entry in the text array, create and append an li
  for (const item of items) {
    const li = document.createElement('li');
    li.textContent = item;
    list.appendChild(li);
  }
}
<input type='text' id='idea' />
<input type='button' value='add to list' id='add' />
<ul id='list'></ul>


推荐阅读