如何实现表单输入匹配关键词数组并支持非精确匹配
实现关键词模糊匹配的页面滚动功能
问题说明
网页顶部表单接收用户输入后,需根据输入内容匹配4组关键词中的任意一个,匹配成功则滚动到对应页面元素。当前代码使用indexOf()仅支持精确匹配(输入需与关键词完全一致),需要改为支持模糊匹配:比如输入"climbing"或"I like climbing"时,能匹配关键词"climb"并触发滚动。
修改后的代码
function answerQuestion() { event.preventDefault(); var answer = document.getElementById("answer").value; answer = answer.toLowerCase().trim(); const hallasanKeyword = ["hiking", "climb", "hike", "outside"]; const udoKeyword = ["cycling", "cycle", "bike"]; const lovelandKeyword = ["art", "fun", "silly"]; const cityKeyword = ["nightlife", "restaurant", "eat"]; if (hallasanKeyword.some(keyword => answer.includes(keyword))) { const hallasan = document.getElementById("hallasan").offsetTop; window.scrollTo({ top: hallasan, behavior: "smooth" }); } else if (udoKeyword.some(keyword => answer.includes(keyword))) { const udo = document.getElementById("udo").offsetTop; window.scrollTo({ top: udo, behavior: "smooth" }); } else if (lovelandKeyword.some(keyword => answer.includes(keyword))) { const loveland = document.getElementById("loveland").offsetTop; window.scrollTo({ top: loveland, behavior: "smooth" }); } else if (cityKeyword.some(keyword => answer.includes(keyword))) { const city = document.getElementById("city").offsetTop; window.scrollTo({ top: city, behavior: "smooth" }); } else { alert("Sorry, what you typed in didn't match any of the keywords on our list! Try something else, or scroll through this page - you might find something you'd like!"); } }
关键改动说明
- 模糊匹配逻辑:用数组的
some()方法遍历关键词组,结合includes()检查用户输入是否包含当前关键词。只要有一个关键词被输入内容包含,就会返回true触发滚动。 - 输入预处理优化:保留
toLowerCase()和trim()确保匹配不区分大小写,同时去除输入前后空格,提升匹配准确性。 - 逻辑优先级保留:依然按原顺序检查四组关键词,确保原有匹配优先级不变。
内容的提问来源于stack exchange,提问作者Rachel
相关产品推荐
相关产品推荐

