如何获取外层filter函数返回值并传入fetch请求的title属性
解决方案
你当前的代码存在3个核心问题,调整后即可正常拿到值赋值给title:
filterID函数没有返回值,内部执行的过滤逻辑结果没有对外抛出,调用时默认拿到undefined- 你用了
filter方法,该方法返回的是匹配元素组成的数组,你需要拿单个匹配元素的内容,用find方法更适配 - 你在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
相关产品推荐
相关产品推荐

