jQuery each函数中$(this).text()返回空字符串问题求助
列表搜索功能中$(this).text()返回空的问题修复
问题根源
你在$.each()里用了箭头函数作为回调,箭头函数不会创建自己的this上下文,它会继承外层作用域的this。这里外层的keyup事件也用了箭头函数,导致$(this)根本指向的不是当前遍历的.users-list-name元素,自然输出空字符串,功能失效。
两种修复方法
方法1:把each的回调改成普通函数
普通函数会自动绑定当前遍历的DOM元素到this上,符合jQuery的预期:
const searchBar = $(".users-layout .search input") searchBar.on("keyup", function() { const searchText = $(this).val().toLowerCase(); if (searchText) { $(".users-list-name").each(function() { const itemText = $(this).text().toLowerCase(); console.log(itemText); if (!itemText.includes(searchText)) { $(this).hide(); } else { $(this).show(); } }); } else { // 搜索框清空时显示所有元素 $(".users-list-name").show(); } })
方法2:用each的参数获取当前元素(保留箭头函数)
如果坚持用箭头函数,可以利用$.each()的第二个参数(当前遍历的DOM元素)来操作:
const searchBar = $(".users-layout .search input") searchBar.on("keyup", () => { const searchText = searchBar.val().toLowerCase(); if (searchText) { $(".users-list-name").each((index, element) => { const itemText = $(element).text().toLowerCase(); console.log(itemText); // 用toggle简化显示/隐藏逻辑 $(element).toggle(itemText.includes(searchText)); }); } else { $(".users-list-name").show(); } })
额外优化建议
- 提前缓存搜索文本的小写版本,避免循环里重复调用
val()和toLowerCase(),提升性能 - 补充搜索框为空时的逻辑,确保所有元素重新显示,功能更完整
- 用
toggle()方法可以把if-else的显示隐藏逻辑简化成一行代码
内容的提问来源于stack exchange,提问作者Leonardo Rosati
相关产品推荐
相关产品推荐

