删除事件只能执行第一行,后面的删除失效:
代码如下
<script>
let id
//通过axios发送异步请求,获取数据
axios.get(' http://localhost:3000/users').then(res => {
//遍历数据
res.data.forEach(function (item) {
//console.log(item)
//获取table对象
var table = document.querySelector('.user-list')
//跟据item中的数据动态创建tr对象
const tr = document.createElement('tr')
tr.innerHTML = `
<td>${item.id}</td>
<td>${item.username}</td>
<td>${item.password}</td>
<td>
<a href="./update.html?id=${item.id}&username=${item.username}&password=${item.password}" class='update'>编辑</a>
<a href="" class='delete'>删除</a>
</td>
`
//将tr添加到table中
table.appendChild(tr)
//删除 ++++++也可以用onclick() function写到外面
document.querySelector('.delete').addEventListener('click', function () {
//confirm 返回true或false
if (confirm('你确定要删除吗?')) {
axios.defaults.baseURL = 'http://localhost:3000/'
axios({
method: 'delete',
url: 'users/' + item.id,
}).then(res=>{
location.href='./index.html' //刷新当前页面
})
}
})
})
})
</script>
纠正:
document.querySelector('.delete').addEventListener('click', function (){.......})
ducoment替换成 tr
问题解决
原因:把点击事件放在data.forEach()中,每遍历一个item创建一个tr,每个tr中包含一个删除事件
如果是document.querySelector....则不被循环(不对document进行循环)
只有tr.querySelector....才会循环,所以源代码中只会执行第一行的删除点击事件