访问从 fetch 内部的外部 filter() 函数返回的值

Access value returned from outer filter() funciton inside fetch

我想访问从 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));
}
})

我发现了几个问题:

  • 您没有对 filter 创建的数组执行任何操作,因此 return item.innerHTML; 也没有执行任何操作——返回的值被放入您从未使用过的数组中。 (传统函数从不执行隐式 return,并且 filterID 函数中没有 return,只有 filter 回调。)
  • 你从不打电话给editTodo
  • 从评论中可以看出您有 collection/list 个 HTML 元素,您正试图找到匹配 todoID 的元素并使用它的 innerHTML在获取调用中。如果是这样,那将是一个 find operation rather than a 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...
    }
});