
本文介绍了如何使用 JavaScript 判断用户在表单中输入的内容是否包含预定义的关键词数组中的任意一个关键词。通过使用 filter 和 includes 方法,可以有效地实现模糊匹配,从而提高用户体验,并引导用户浏览特定内容。本文提供了详细的代码示例和解释,帮助开发者轻松实现这一功能。
在 Web 开发中,经常需要根据用户的输入内容执行不同的操作。一个常见的场景是,根据用户输入的关键词,将页面滚动到特定的位置。如果需要匹配多个关键词,并且允许用户输入的内容包含关键词即可,而不需要完全匹配,可以使用以下方法。
实现原理
核心思想是使用数组的 filter 方法结合字符串的 includes 方法。filter 方法用于筛选出数组中满足条件的元素,includes 方法用于判断字符串是否包含指定的子字符串。
代码示例
以下是一个完整的代码示例,演示了如何判断用户输入是否包含关键词数组中的任意关键词:
function answerQuestion() {
event.preventDefault();
var answer = document.getElementById("answer").value;
answer = answer.toLowerCase();
answer = answer.trim();
const hallasanKeyword = [
"hiking",
"climb",
"hike",
"outside",
];
const udoKeyword = [
"cycling",
"cycle",
"bike",
];
const lovelandKeyword = [
"art",
"fun",
"silly",
];
const cityKeyword = [
"nightlife",
"restaurant",
"eat",
];
if ((hallasanKeyword.filter(item => answer.includes(item))).length > 0) {
var hallasan = document.getElementById("hallasan").offsetTop;
window.scrollTo({ top: hallasan, behavior: "smooth" });
} else if ((udoKeyword.filter(item => answer.includes(item))).length > 0) {
var udo = document.getElementById("udo").offsetTop;
window.scrollTo({ top: udo, behavior: "smooth" });
} else if ((lovelandKeyword.filter(item => answer.includes(item))).length > 0) {
var loveland = document.getElementById("loveland").offsetTop;
window.scrollTo({ top: loveland, behavior: "smooth" });
} else if ((cityKeyword.filter(item => answer.includes(item))).length > 0) {
var 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!"
);
}
}代码解释
注意事项
总结
通过使用 filter 和 includes 方法,可以方便地判断用户输入是否包含关键词数组中的任意关键词。这种方法简单易懂,并且能够满足大多数应用场景的需求。在实际开发中,可以根据具体情况进行适当的调整和优化。
以上就是如何判断用户输入是否包含关键词数组中的任意关键词?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号