html - 当用户在输入字段中输入以逗号分隔的值时。如何以列表格式显示输出
问题描述
在此输入字段中。当用户输入一个以逗号分隔的值时。例如像“苹果、香蕉、葡萄、芒果”。因此,如果用户以这种格式输入值。然后我想以列表格式显示输出,例如
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,你需要创建正确的列表项对象并附加这些:
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>
推荐阅读
- excel - 在 Excel 版本 365 上为旧版本(即 Excel 2012)开发 VBA 应用程序
- facebook - Facebook API 上线时返回空集
- python - 如何根据python中的当前时间更改变量?
- mtrace - 在哪里可以找到用于读取 MALLOC_TRACE 环境变量输出的“mtrace”Perl 脚本?
- javascript - 在 TypeScript 中,当面向 IE11(ES5)时,如何扩展位于另一个文件中的基类?
- c++ - 使用 GLM 在 OpenGL 中进行轨道和自旋旋转
- swift - 如何创建协议委托以观察 Alamofire 进度并在 ViewController swift 中使用
- java - iText7:我们可以在将 html 转换为 pdf 时指定多个基本 Uri 吗?
- javascript - 如何使用 Thymeleaf 在 Spring 中将 Java 对象与表行绑定?
- jquery - 获取所选项目