我正在尝试使用获取中的元素动态生成一张表,我可以与用户一起绘制该表,但是我想向每行添加一个onclick函数,因此每当单击在我将图书分配给该用户(从数据库获取)的行中,无论如何,我的问题是,每次生成tr时,如何在每个tr中添加函数,所以当我单击tr时,我会调用一个函数。我试图在drawUsersTable function
上向每个tr添加一个事件侦听器,但似乎不起作用。这是代码:
<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方法,而是在scren上打印了所有代码。...有什么提示吗?
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);
}
答案 0 :(得分:1)
您在哪里
global.XMLHttpRequest = require('xhr2');
您不能添加:
const tr = document.createElement("tr");
答案 1 :(得分:0)