javascript 如何在自动生成的元素中添加onclick事件

s3fp2yjn  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(101)

我试图动态地生成一个表格,我通过一个获取的元素,我得到了绘制用户的表格,但我想添加一个onclick功能的每一行,所以每当我点击行我得到的书附加到该用户(从数据库中获得),无论如何,我的问题是,我如何在每次生成一个tr时向每个tr添加一个函数,以便当我单击一个tr时,我调用一个函数。我尝试在drawUsersTable function上为每个tr添加一个eventlistener,但似乎不起作用。
下面是代码:

<body>
    <script>
      async function getToken() {
        const response = await fetch("http://localhost:3000/auth", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            user: "jesus",
            password: "1234"
          })
        });
        const { token } = await response.json(); //esta linea no se ejecutara hasta que response este resuelta
        localStorage.setItem("token", token);
      }

      async function printUsers() {
        const token = localStorage.getItem("token");
        const response = await fetch("http://localhost:3000/users", {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        });
        const users = await response.json();
        drawUsersTable(users);
      }

      const drawUsersTable = users => {
        cont = 1;
        const table = document.getElementById("table");
        users.forEach(({ user_id, username, isAdmin }) => {
          
          const firstTD = document.createElement("td");          
          const secondTD = document.createElement("td");
          const thirdTD = document.createElement("td");

          firstTD.innerText = user_id;
          secondTD.innerText = username;
          thirdTD.innerText = isAdmin;

          const tr = document.createElement("tr");
          tr.setAttribute("id", "user_id" + cont);
          tr.addEventListener("click", printBooks(user_id));
          cont = cont + 1;
          tr.append(firstTD, secondTD, thirdTD);
          table.append(tr);
        });
      };
      getToken().then(() => printUsers());

      async function printBooks(userId) {    
        const token = localStorage.getItem("token");        
        const response = await fetch("http://localhost:3000/bookUser/:userId/books", {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json"
          }
        });
        const books = await response.json();
        console.log(books);
      }

    </script>

    <table id="table">
      <tr>
        <td class="id">ID</td>
        <td>Username</td>
      </tr>
    </table>

我尝试了这个方法,但它不起作用,而不是将onclick方法添加到每一行,它会打印出屏幕上的所有代码。有什么提示吗?

const drawUsersTable = users => {
        cont = 1;
        const table = document.getElementById("table");
        users.forEach(({ user_id, username, isAdmin }) => {
          const firstTD = document.createElement("td");
          const secondTD = document.createElement("td");
          const thirdTD = document.createElement("td");

          firstTD.innerText = user_id;
          secondTD.innerText = username;
          thirdTD.innerText = isAdmin;

          const tr = document.createElement("tr");
          tr.setAttribute("id", "user_id" + cont);
          tr.onclick =  function(user_id){
            const token = localStorage.getItem("token");
            const response =  fetch("http://localhost:3000/bookUser/:userId/books", {
              headers: {
               Authorization: `Bearer ${token}`,
              "Content-Type": "application/json"
              }
            });
            const books =  response.json();
            console.log(books);
          }
hlswsv35

hlswsv351#

你在哪里

const tr = document.createElement("tr");

你能不加:

tr.onclick = function() { alert('magic'); };
nc1teljy

nc1teljy2#

element.onclick = functionName()应该可以工作。

在这里检查代码

https://jsfiddle.net/Arpit09/dbxzuyre/17/

相关问题