This article mainly introduces the search and highlighting functions implemented by JavaScript, involving operating techniques related to javascript character traversal and page element attributes. Friends who are interested in JavaScript can refer to this article
Scenario: is used to filter the data in the list. Since the single data is very short, php+mysql is not used to implement the filtering function. Only javascript is used to filter, highlight the matching, or Hide those that do not match
Rendering:
##html:
<p class="contracts-header">名称: <input type="text" value="" id="search_contract_name"></p> <p class="contracts-header">代码: <input type="text" value="" id="search_contract_code" placeholder="不区分大小写"></p> <p class="contracts-header"><button onclick="search()">查找</button></p> <p 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> </p>
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 Constructor Pattern Instance Analysis
How does JavaScript calculate the object length
Detailed explanation of typeof and type judgment in javascript
The above is the detailed content of Example of search and highlighting functions implemented in JavaScript. For more information, please follow other related articles on the PHP Chinese website!