本文实例讲述了JavaScript实现的搜索及高亮显示功能。分享给大家供大家参考,具体如下:
本文实例讲述了JavaScript实现的搜索及高亮显示功能。分享给大家供大家参考,具体如下:
情景: 用来筛选列表中的数据, 由于单条数据很简短, 没有用php+mysql去实现筛选功能, 只用javascript进行筛选, 匹配的高亮, 或者将不匹配的隐藏掉
效果图:
html:
<div class="contracts-header">名称: <input type="text" value="" id="search_contract_name"></div>
<div class="contracts-header">代码: <input type="text" value="" id="search_contract_code" placeholder="不区分大小写"></div>
<div class="contracts-header"><button onclick="search()">查找</button></div>
<div id="contracts-list">
<ul>
<li><input type="checkbox" name="contract[]" value="code|name" /><span>name(code)</span></li>
<li><input type="checkbox" name="contract[]" value="code|name" /><span>name(code)</span></li>
</ul>
</div>
javascript:
function search()
{
var search_contract_name = $("#search_contract_name").val();
var search_contract_code = $("#search_contract_code").val();
if (search_contract_name && search_contract_code) { //两个输入框都有值
search_contract_code = search_contract_code.toLowerCase(); //不区分大小写, 全部转换为小写, 下同
$("input[name='contract[]']").each(
function () {
var code_name = this.value;
var search_code = code_name.toLowerCase().indexOf(search_contract_code);
var search_name = code_name.toLowerCase().indexOf(search_contract_name);
if (search_code >=0 && search_name >=0 ) {
// this.nextSibling.style.backgroundColor = "#FFDEAD"; //高亮匹配到的
this.parentNode.style.display = 'block';
} else {
// this.nextSibling.style.backgroundColor = "";
this.parentNode.style.display = 'none'; //隐藏不匹配的
}
}
);
} else if(search_contract_name || search_contract_code) { //只有一个输入框有值
search_contract_name = search_contract_name.length ? search_contract_name : 'xxx'; //默认为xxx是因为不可能存在xxx
search_contract_code = search_contract_code.length ? search_contract_code.toLowerCase() : 'xxx';
$("input[name='contract[]']").each(
function () {
var code_name = this.value;
var search_code = code_name.toLowerCase().indexOf(search_contract_code);
var search_name = code_name.toLowerCase().indexOf(search_contract_name);
if (search_code >=0 || search_name >=0 ) {
// this.nextSibling.style.backgroundColor = "#FFDEAD";
this.parentNode.style.display = 'block';
} else {
// this.nextSibling.style.backgroundColor = "";
this.parentNode.style.display = 'none';
}
}
);
}
}
JavaScript
搜索
高亮