javascript - 在字符串中搜索以任意顺序输入的单词
问题描述
在以下示例中:
<li class="link" data-tag="these are tags to help find the link within the list"><a href="https://www.google.com" target="_blank">Super cool link</a></li>
<li class="link" data-tag="another TAG for awesome site"><a href="https://www.google.com" target="_blank">Another Awesome and Cool Site</a></li>
这两个列表项包含一个名为的自定义属性data-tag
,在列表项中,有一个包含任何文本的超链接。
我想以任何顺序输入任何单词,并隐藏任何<li></li>
与总单词不匹配的标签。
现在使用下面的 javascript...
$(document).on("input", "#find-link", function() {
// Get the value of the textbox
var linkSearchValue = $(this).val().toLowerCase();
// Cycle through the list of links
$(".link").each(function(i) {
// If the searchbox is NOT empty
if (linkSearchValue != "") {
// Get the tags and text to compare against
var linkTags = $(this).attr("data-tag");
var linkText = $(this).text();
if ( (!linkTags.toLowerCase().includes(linkSearchValue)) && (!linkText.toLowerCase().includes(linkSearchValue)) ) { // Check if the search string DOESN'T match...
// If there isn't a match for a link, hide it.
$(this).addClass("hidden-link");
} else {
// If there IS a match for a link, show it.
$(this).removeClass("hidden-link");
}
} else {
$(this).removeClass("hidden-link");
}
});
});
我可以按顺序在文本框中输入单词……例如,“cool”将显示两个链接。“真棒”仅显示第二个链接。但是,如果我输入“cool awesome”,则两个链接都不会显示。
如何更好地构建 JavaScript 代码(jQuery 或纯 JS 都可以)以忽略单词的顺序,而只查找单词的实例或一系列字符?我在想我必须要么将结果转换成数组$(this).attr("data-tag");
,$(this).text();
但我不知道该怎么做,我完全被难住了。
解决方案
推荐阅读
- python-3.x - PySpark - 在我的 win10 笔记本电脑上运行 spark 线性回归模型时出现 py4j.protocol.Py4JJavaError
- asp.net - 如何结合 Facebox 和 OnselectedIndex 功能
- ajax - 从数据库加载值
- java - 在服务器上部署时java图形drawString错误字体
- java - 如何比较 if 语句中的布尔值与输出 Java
- macos - MacOS 上的 Arduino 禁用了我的 USB 端口
- javascript - 为 div 创建 cookie
- node.js - 原生 Promise 和 bluebird Promise 的区别
- jquery - 设置图像的 src 时显示/隐藏占位符
- javascript - 未捕获的类型错误:无法读取未定义的属性“toString”如何删除 rawMarkUp 中代码的依赖关系?