外部过滤器()函数内部获取返回的访问值



我想访问fetch属性内部的外部函数返回的值。该值正在注销,但我需要在'title'属性内获取的值。如果这是一个无关的问题,请原谅,我是新手。需要解决方案或替代方案。

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));
}
})

我看到了几个问题:

  • 您没有对filter创建的数组做任何事情,因此return item.innerHTML;不做任何事情-返回的值被放入您从未使用过的数组中。(传统的函数从来没有隐式的return,在你的filterID函数中没有return,只有filter回调)
  • 永远不要呼叫editTodo
  • 从评论中听起来,你有一个HTML元素的集合/列表,你试图找到一个匹配todoID并在fetch调用中使用它的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));
}
});

或者在todoItem上使用for-of循环,因为NodeList(来自querySelectorAll)和HTMLCollection(来自getElementsByXYZ方法)都是可迭代的(像数组一样):

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...
}
});

最新更新