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

使用jQuery Toggle时无匹配项如何显示提示信息

解决jQuery Toggle无匹配条目时显示提示的问题

你的代码已经实现了根据搜索内容切换条目的显示隐藏,但缺少对匹配结果数量的统计,所以没法判断什么时候显示无匹配提示。可以按以下步骤修改:

  • 先定义一个计数器,用来统计匹配成功的条目数
  • 在遍历每个dl dd时,判断如果匹配成功,就把计数器加1,同时保持toggle显示逻辑
  • 遍历结束后,根据计数器是否为0,控制提示元素的显示(提前在页面里加一个隐藏的提示,比如<div class="no-match" style="display:none;">未找到匹配条目</div>)

修改后的代码如下:

const userSearch = ($("#userId").val() || '').toLowerCase();
let matchCount = 0; // 新增计数器

$('.table tbody tr').find("dl dd").each(function() {
  const userfilter = $(this);
  const userNames = userfilter[0].innerText.toLowerCase();
  // 简化匹配判断:直接检查是否包含搜索关键词即可,原逻辑的substring判断没必要
  const isMatch = userNames.includes(userSearch);
  
  userfilter.toggle(isMatch);
  if (isMatch) {
    matchCount++; // 匹配成功则计数器加1
  }
});

// 控制提示信息的显示/隐藏
$('.no-match').toggle(matchCount === 0);

另外提个小优化:原代码里用substring加indexOf的匹配逻辑有点绕,直接用includes()方法判断关键词是否存在会更简洁准确,避免indexOf返回-1时substring截取整个字符串导致的误匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:54:55