javascript - 事件侦听器需要在 DOM 更新之前单击两次
问题描述
我的网页有一个表格,其中包含从数据库中提取的数据——它几乎是数据库的克隆。表中的每一行都有一个删除按钮和一个更新按钮,允许用户删除相应的数据库行,或使用提供的表单更新列。
我的问题是删除和更新按钮都不能正常工作。第一次单击对数据库进行了适当的更改,但表保持不变,直到第二次单击该按钮。
let loadUsers = function () {
fetch("http://localhost:8080/users").then(function (response) {
response.json().then(function (data) {
// generate table and delete/update button html
data.forEach(function (user) {
deleteButton = document.querySelector("#btn-del-user);
deleteButton.onclick = function () {
if (confirm("Are you sure you want to delete " + user.firstname + "?")) {
deleteUser(user.id);
loadUsers();
}
});
}
});
};
loadUsers();
document.addEventListener('submit', function(event) {
if (!event.target.matches('#update-user-form')) return;
let elements = document.querySelector('#update-user-form').elements;
let inputs = {
"firstName": elements.firstName.value,
"lastName": elements.lastName.value,
"email": elements.email.value,
"password": elements.password.value
};
let body = "";
// create a URL-encoded string from form inputs
Object.keys(inputs).forEach(function (key, i) {
body += key + "=" + encodeURIComponent(inputs[key]);
if (i < Object.keys(inputs).length - 1) {
body += "&";
}
});
let id = elements["user-id"].value;
fetch('http://localhost:8080/users/' + id, {
method: 'UPDATE',
body: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
loadUsers();
});
奇怪的是,我在页面上有一个单独的表单,可让我向表/数据库添加新行,并且该表单的侦听器也调用loadUsers()
,但单击后成功更新了 DOM。
解决方案
loadUsers 需要等待更新/删除完成才能再次加载用户
尝试
fetch('http://localhost:8080/users/' + id, {
method: 'UPDATE',
body: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(loadUsers);
推荐阅读
- docx4j - w:t 不是 org.docx4j.wml.Text 的实例?
- excel - 使用excel宏删除PowerPoint幻灯片中的所有图表
- qt - 如何获取 QTreeWidgetItem 数据?
- google-cloud-platform - GCP 通过 API 为 Bitbucket 设置 Cloud Build Trigger
- javascript - XML 到 Javascript/Jquery 可读格式
- c++ - 我应该在我的函数中使用静态变量来防止重新计算值吗?
- javascript - AJAX 响应函数(防止异步错误)
- debugging - eldoc 模式在获取要在 echo 中显示的信息时挂起 emacs
- java - 如何在eclipse中删除方法和属性上方的搜索参考链接
- kubernetes - 无法连接到部署在其他节点上的 pod