首页 > 解决方案 > 事件侦听器需要在 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。

标签: javascriptrest

解决方案


loadUsers 需要等待更新/删除完成才能再次加载用户

尝试

fetch('http://localhost:8080/users/' + id, {
    method: 'UPDATE',
    body: body,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
}).then(loadUsers);

推荐阅读