我想訪問從 fetch 屬性內的外部函式回傳的值。該值正在注銷,但我需要在 'title' 屬性中獲取 fetch 中的值。如果這是一個無關緊要的問題,請原諒我,我對此很陌生。需要解決方案或替代方案。
button.addEventListener('click', (e) => {
function editTodo(e) {
function filterID() {
Array.from(todoItem).filter((item) => {
if (item.getAttribute('id') == todoID) {
console.log(item.innerHTML);
return item.innerHTML;
}
});
} //<<value is being logged out
fetch(`${url}/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: filterID(), //<<need to access here
}),
})
.then((res) => {
setMessage('Updated');
return res.json();
})
.catch((error) => console.log(error));
}
})
uj5u.com熱心網友回復:
我看到幾個問題:
- 你沒有對
filter創建的陣列做任何事情,所以return item.innerHTML;它什么也不做——回傳的值放在你從未使用過的陣列中。(傳統函式從不執行 hiddenreturn,并且return您的filterID函式中沒有,只有filter回呼。) - 你從不打電話
editTodo。 - 從評論中聽起來,您有一個 HTML 元素的集合/串列,并且您正在嘗試找到匹配的元素并在 fetch 呼叫中
todoID使用它innerHTML。如果是這樣,那將是一個find操作而不是一個filter操作。
看評論:
button.addEventListener("click", (e) => {
// Where is `editTodo` used??
function editTodo(e) {
// `todoItem` really should be plural if it"s a collection/list/array
// Use `find` to find the matching `todo`, and then use `innerHTML` on it
const todo = Array.from(todoItem).find((item) => item.getAttribute("id") === todoID);
if (!todo) {
return; // Not found
}
fetch(`${url}/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: todo.innerHTML, // ***
}),
})
.then((res) => {
setMessage("Updated");
return res.json();
})
.catch((error) => console.log(error));
}
});
或者使用for-of回圈,todoItem因為NodeList(from querySelectorAll) 和HTMLCollection(fromgetElementsByXYZ方法) 都是可迭代的(就像陣列一樣):
button.addEventListener("click", (e) => {
// Where is `editTodo` used??
function editTodo(e) {
// `todoItem` really should be plural if it"s a collection/list/array
// Use `find` to find the matching `todo`, and then use `innerHTML` on it
let todo = null;
for (const item of todoItem) {
if (item.getAttribute("id") === todoID) {
todo = item;
break;
}
}
if (!todo) {
return; // Not found
}
// ...same otherwise...
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338413.html
標籤:javascript 功能 筛选 范围 拿来
