You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取外层filter函数返回值并传入fetch请求的title属性

解决方案

你当前的代码存在3个核心问题,调整后即可正常拿到值赋值给title:

  1. filterID 函数没有返回值,内部执行的过滤逻辑结果没有对外抛出,调用时默认拿到undefined
  2. 你用了filter方法,该方法返回的是匹配元素组成的数组,你需要拿单个匹配元素的内容,用find方法更适配
  3. 你在click事件回调里只定义了editTodo函数,没有主动调用,点击后逻辑根本不会执行

修复后的代码如下:

button.addEventListener('click', (e) => {
  function editTodo(e) {
    function filterID() {
      // 用find找第一个匹配的元素,同时把结果return给filterID函数
      const matchedItem = Array.from(todoItem).find((item) => {
        return item.getAttribute('id') == todoID
      })
      // 匹配到才返回innerHTML,匹配不到返回空字符串避免接口传参异常
      return matchedItem ? matchedItem.innerHTML : ''
    }

    fetch(`${url}/${id}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 
        title: filterID(),
      }),
    })
    .then((res) => {
        setMessage('Updated');
        return res.json();
    })
    .catch((error) => console.log(error));
  }
  // 主动调用定义好的editTodo函数,触发逻辑执行
  editTodo(e)
})

如果不想额外定义filterID函数,也可以直接把匹配逻辑写在title赋值的位置,简化代码:

body: JSON.stringify({
  title: Array.from(todoItem).find(item => item.getAttribute('id') == todoID)?.innerHTML || ''
})

内容的提问来源于stack exchange,提问作者Ansul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:18:01