js商品列表的添加删除
时间: 2023-10-01 21:09:10 浏览: 101
你可以使用 JavaScript 创建一个商品列表,然后通过添加和删除功能来维护该列表。以下是一个简单的示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>商品列表</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>商品列表</h1>
<input type="text" id="input">
<button onclick="addItem()">添加商品</button>
<ul id="list"></ul>
<script>
var list = document.getElementById("list");
function addItem() {
var input = document.getElementById("input");
var item = document.createElement("li");
item.innerHTML = input.value;
list.appendChild(item);
input.value = "";
}
function removeItem() {
list.removeChild(this);
}
list.addEventListener("click", removeItem);
</script>
</body>
</html>
```
在这个示例中,我们创建了一个输入框和一个“添加商品”按钮,用于向列表中添加新的商品。我们还创建了一个空的 `<ul>` 元素,用于显示商品列表。在 JavaScript 中,我们定义了一个 `addItem()` 函数,用于创建一个新的 `<li>` 元素,并将其添加到列表中。我们还定义了一个 `removeItem()` 函数,用于从列表中删除商品。最后,我们将 `removeItem()` 函数绑定到列表的 `click` 事件上,以便在用户单击某个商品时删除它。
你可以根据自己的需求修改该示例,例如添加更多的输入字段,或者使用数据库来存储商品列表等。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)