[英]Calling the function on every iteration of for loop in Javascript
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table =
"<tr><th>Title</th><th>Author</th><th>Cover Page</th><th>Ratings</th></tr>";
var x = xmlDoc.getElementsByTagName("best_book");
for (i = 0; i < x.length; i++) {
bookname = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
authorname = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
table +=
"<tr><td class='book'>" +
bookname +
"</td><td class='author'>" +
authorname +
"</td><td>" +
"<img src='" +
x[i].getElementsByTagName("image_url")[0].childNodes[0].nodeValue +
"' height='100px' width='70px'>" +
"</td><td>" +
"<div class='stars' data-rating='1'>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<span class='star'> </span>" +
"<input type='button' value='Add Rating' onClick = 'submitRating()'>" +
"</div>" +
"</td></tr>";
console.log(bookname);
}
document.getElementById("result").innerHTML = table;
}
async function submitRating() {
try {
let boo = bookname;
console.log(boo);
let auth = authorname;
console.log(auth);
let rat = 5;
console.log(rat);
let data = JSON.stringify({
author: auth,
book: boo,
rating: rat
});
console.log(data);
let res = await fetch(hostUrl + "api/ratings", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json"
}
});
console.log(res);
res.json().then(matter => {
console.log(matter);
});
// let myJson = res.json();
// console.log(myJson);
if (res.status == 200) {
console.log("the status is " + res.status);
} else {
console.log("the status is " + res.status);
alert("rating not given");
}
} catch (error) {
console.log("Error:" + error);
}
}
我試圖在 for 循環的每次迭代中調用submitRating
函數,但我沒有在JavaScript 中獲得正確的方法。 現在,在運行循環后, onclick = submitRating()
函數只提交 mongodb 中的最后一個值。 有人可以幫我嗎?
這是因為bookname
和authorname
保留了由 for 循環的最后一次迭代設置的最后一個值。 換句話說,這些變量會被多次覆蓋,直到 for 循環結束。 如果您想在每個項目的基礎上存儲這些信息,您可以將它們存儲在 HTML5 data-
屬性中並在 onclick 處理程序中檢索它們。
例如,您可以這樣做:
"<input type='button' value='Add Rating' data-bookname='"+bookname+"' data-authorname='"+authorname+"' onClick='submitRating(this)' />"
然后,在您的submitRating
方法中,您可以簡單地使用Element.dataset
讀取信息:
async function submitRating(el) {
const bookname = el.dataset.bookname;
const authorname = el.dataset.authorname;
// More logic here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.