jQuery实现搜索过滤后选中首个匹配项及回车自动触发点击
实现搜索输入框自动选中首个匹配项并回车触发跳转
嘿,我来帮你搞定这个需求!我们需要分几步实现:一是输入搜索文本时自动选中第一个过滤后的匹配项,二是按下回车键时触发这个选中项的跳转。不过先得修正一下你的Pug模板小问题,不然后续的jQuery逻辑会出问题~
第一步:修正Pug模板结构
你原来的代码里,for prop in stationName是在ul外面的,这会导致每个车站都生成一个独立的#mylist列表,这样jQuery选择器无法正确选中所有列表项。我们需要把ul放到循环外面,让所有列表项都归属于同一个列表:
.row .col-md-8.offset-md-2.pad .form(class="form-row justify-content-center deparrSearchForm") .form-group.col-md-8 input(type="text" class="form-control form-control-lg" id="fromStation" name="fromStation" placeholder="Type train station name & press enter") //- 把ul容器移到循环外层,所有列表项都在同一个列表下 ul(class="list-group text-center" id="mylist") for prop in stationName a(href="/train/search-deparrtrain-submit/"+prop.stationShortCode+'/'+prop.stationName) li(class="list-group-item") #{prop.stationName}
第二步:修改jQuery逻辑实现需求
接下来我们修改你的jQuery代码,添加选中第一个匹配项和回车触发点击的功能:
$("#fromStation").on("keyup", function(e) { // 优先处理回车键事件 if (e.keyCode === 13) { // 找到第一个被选中的列表项的父级链接,触发跳转 const $targetLink = $("#mylist .list-group-item.active").parent("a"); if ($targetLink.length) { $targetLink[0].click(); // 使用原生click方法避免jQuery事件冒泡问题 } return; // 回车后跳过后续过滤逻辑 } const searchText = $(this).val().toLowerCase(); const $allListItems = $("#mylist li"); // 过滤列表项:匹配的显示,不匹配的隐藏 $allListItems.each(function() { const itemText = $(this).text().toLowerCase(); $(this).toggle(itemText.indexOf(searchText) >= 0); }); // 移除所有列表项的选中状态 $allListItems.removeClass("active"); // 给第一个可见的匹配项添加选中样式 const $firstMatch = $allListItems.filter(":visible").first(); if ($firstMatch.length) { $firstMatch.addClass("active"); } });
第三步:添加选中状态的视觉样式
为了让用户直观看到哪个项被选中,我们可以给.active类添加样式:
.list-group-item.active { background-color: #007bff; border-color: #007bff; color: #fff; }
代码逻辑说明:
- 回车键处理:当用户按下回车时,我们找到带有
active类的列表项的父级<a>标签,触发它的点击事件完成跳转。 - 列表过滤:用
toggle方法简化显示/隐藏的判断逻辑,比分开写show/hide更简洁。 - 选中第一个匹配项:过滤完成后,先清除所有项的选中状态,再给第一个可见的匹配项加上
active类,确保每次搜索后都选中首个结果。
内容的提问来源于stack exchange,提问作者Shekhar Aryal
相关产品推荐
相关产品推荐

