我有一个动态列表,它在项目加载时添加项目。
<ul id="dynamic-list"></ul>请参见函数addItem()
我需要做的是当从有序列表中选择一个项目时触发的事件。
因为我没有< li>标签,所以我不能在这里设置onclick。
有没有办法在javascript文档中添加或设置每个il都有onclick事件?
document.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamically add/remove items from list - JavaScript</title>
</head>
<body>
<ul id="dynamic-list"></ul>
<input type="text" id="candidate"/>
<button onclick="addItem()">add item</button>
<button onclick="removeItem()">remove item</button>
<p id="textoprueba"></p>
<script src="script.js"></script>
</body>
</html>script.js
function addItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var li = document.createElement("li");
li.setAttribute('id',candidate.value);
li.appendChild(document.createTextNode(candidate.value));
ul.appendChild(li);
}
function removeItem(){
var ul = document.getElementById("dynamic-list");
var candidate = document.getElementById("candidate");
var item = document.getElementById(candidate.value);
ul.removeChild(item);
}发布于 2020-06-26 00:48:52
您始终可以在列表项中添加按钮,并在以后使用css来对齐和对齐内容。
<li>
<span>List item text</span>
<button onclick="removeItem()">button</button>
</li>或者甚至将整个列表项包装在一个按钮容器中,这并不直观,也不是设计方面的最佳选择。
<button onclick="removeItem()">
<li>List item text</li>
</button>只需记住在remove函数中传递列表项的id即可。
https://stackoverflow.com/questions/62580071
复制相似问题