使用下面的数组生成一个新闻列表,并能点击删除每条新闻
时间: 2024-04-30 11:21:16 浏览: 12
好的,我可以帮您实现这个功能。以下是示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>News List</title>
<style>
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border: 1px solid #ccc;
margin-bottom: 5px;
}
li:hover {
background-color: #f9f9f9;
}
.delete {
cursor: pointer;
color: red;
}
</style>
</head>
<body>
<ul id="news-list"></ul>
<script>
const news = [
{ title: "Lorem ipsum dolor sit amet", date: "2021-06-01" },
{ title: "Consectetur adipiscing elit", date: "2021-06-02" },
{ title: "Sed do eiusmod tempor incididunt", date: "2021-06-03" },
{ title: "Ut labore et dolore magna aliqua", date: "2021-06-04" },
{ title: "Ut enim ad minim veniam", date: "2021-06-05" }
];
const list = document.getElementById("news-list");
// Loop through the news array and create a list item for each news item
news.forEach((item, index) => {
const li = document.createElement("li");
li.innerHTML = `<span>${item.title}</span><span>${item.date}</span><span class="delete" data-index="${index}">X</span>`;
list.appendChild(li);
});
// Add event listener for the delete button
list.addEventListener("click", (e) => {
if (e.target.classList.contains("delete")) {
const index = e.target.getAttribute("data-index");
news.splice(index, 1); // Remove the news item from the array
list.removeChild(e.target.parentNode); // Remove the list item from the DOM
}
});
</script>
</body>
</html>
```
这段代码会生成一个新闻列表,每一条新闻都有一个删除按钮,点击按钮可以删除该条新闻。您可以在 `news` 数组中添加或删除新闻来测试这个功能。