【发布时间】:2016-07-14 16:16:58
【问题描述】:
所以我正在尝试在页面上实现基本的搜索功能。我有一个由多个<div> 和一个搜索栏<input> 构成的页面,如下所示:
<input id="search" type="text">
<div class="panel-flex">
<h4>Title One</h4>
</div>
<div class="panel-flex">
<h4>Title Two</h4>
</div>
<div class="panel-flex">
<h4>Title Three</h4>
</div>
当您在搜索栏中输入时,任何不包含当前值的<h4> 都将从页面中删除。到目前为止,这是我的代码,但我找不到让部分搜索匹配发生的方法,只有完全匹配。
例如,如果您搜索 t,则所有内容都会显示,但如果您搜索 th,则只有 Title Three 会显示。
$(document).ready(function() {
$("#search").on("keyup", function() {
var searchTerm = $(this).val();
$(".panel-flex").each(function() {
$(this).hide();
if ($(this).find("h4").text() == searchTerm) {
$(this).show();
}
});
});
});
我想要一些类似于 PHP 的 strpos() 函数的东西,所有的调查都让我找到了 JavaScript 函数 indexOf(),但尝试在我的代码中实现它会更糟。
$(document).ready(function() {
$("#search").on("keyup", function() {
var searchTerm = $(this).val();
$(".panel-flex").each(function() {
$(this).hide();
if ($(this).find("h4").indexOf(searchTerm) != -1) {
$(this).show();
}
});
});
});
【问题讨论】:
-
indexof 是正确的工具,但直接的问题是您在元素上调用它而不是元素的文本,它适用于字符串
标签: javascript jquery html indexof