如何使用 JavaScript 在无序列表 (UL) 中添加换行符?
javascriptweb developmentobject oriented programming更新于 2025/11/6 0:12:17
要在无序列表中添加换行符,请使用 document.querySelector().append()。以下是代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
h1{
font-size: 2.50rem;
}
h2, label{
font-size: 1.50rem;
}
</style>
</head>
<body>
<h1>Adding Name Demo</h1>
<div>
<label>Enter The Name:</label>
<input class="txtName" type="text" />
<button class="btnName">Save</button>
</div>
<h2>List Of Name</h2>
<ul class="listOfName"></ul>
<script>
const buttonName = document.querySelector('.btnName')
const addName = e => {
let nameTxt = document.querySelector('.txtName'),
name = nameTxt.value.trim()
if (name) {
let tagLi = document.createElement('li')
tagLi.textContent = name
document.querySelector('.listOfName').append(tagLi)
nameTxt.value = ''
}
}
buttonName.addEventListener('click', addName)
</script>
</body>
</html>
要运行上述程序,请保存文件名"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择选项"使用 Live Server 打开"。
输出
将产生以下输出 −

在这里,我在文本框中输入值,例如名字是"John" −

之后,点击保存按钮。点击保存按钮后,输出如下 −

再次,我输入了名字"Bob"。现在,更新后的输出如下 −

点击保存按钮后,输出如下 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

