这篇文章主要介绍了javascript实现的搜索及高亮显示功能,涉及javascript字符遍历与页面元素属性相关操作技巧,对javascript感兴趣的朋友可以参考下本篇文章
情景: 用来筛选列表中的数据, 由于单条数据很简短, 没有用php+mysql去实现筛选功能, 只用javascript进行筛选, 匹配的高亮, 或者将不匹配的隐藏掉
效果图:

html:
立即学习“Java免费学习笔记(深入)”;
名称:
代码:
- name(code)
- name(code)
javascript:
主要更新介绍: 完美整合Discuz!论坛,实现一站式登陆、退出、注册; 同步所有会员资料; 新增购物车功能,商品购买更加方便、快捷; 新增部分快捷菜单,网站访问更加方便; 限制首页商品、店铺标题显示长度; 修正会员后台管理不能更改密码的错误; 完善商品显示页面所有功能链接; 修正后台标签管理部分错误; 修正前台学校列表不按后台顺序显示的错误; 修正搜索功能中学校名称过长导致显示紊乱的现象; 修正
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提供到一定的帮助!!
相关推荐:










