2015年12月22日 15:45:08 星期二
情景: 用来筛选列表中的数据, 由于单条数据很简短, 没有用php+mysql去实现筛选功能, 只用javascript进行筛选, 匹配的高亮, 或者将不匹配的隐藏掉
效果图:
html:
1 <div class="contracts-header">名称: <input type="text" value="" id="search_contract_name"></div> 2 <div class="contracts-header">代码: <input type="text" value="" id="search_contract_code" placeholder="不区分大小写"></div> 3 <div class="contracts-header"><button onclick="search()">查找</button></div> 4 5 <div id="contracts-list"> 6 <ul> 7 <li><input type="checkbox" name="contract[]" value="code|name" /><span>name(code)</span></li> 8 <li><input type="checkbox" name="contract[]" value="code|name" /><span>name(code)</span></li> 9 </ul> 10 </div>
javascript:
1 function search() 2 { 3 var search_contract_name = $("#search_contract_name").val(); 4 var search_contract_code = $("#search_contract_code").val(); 5 6 if (search_contract_name && search_contract_code) { //两个输入框都有值 7 search_contract_code = search_contract_code.toLowerCase(); //不区分大小写, 全部转换为小写, 下同 8 $("input[name='contract[]']").each( 9 function () { 10 var code_name = this.value; 11 var search_code = code_name.toLowerCase().indexOf(search_contract_code); 12 var search_name = code_name.toLowerCase().indexOf(search_contract_name); 13 if (search_code >=0 && search_name >=0 ) { 14 // this.nextSibling.style.backgroundColor = "#FFDEAD"; //高亮匹配到的 15 this.parentNode.style.display = 'block'; 16 } else { 17 // this.nextSibling.style.backgroundColor = ""; 18 this.parentNode.style.display = 'none'; //隐藏不匹配的 19 } 20 } 21 ); 22 } else if(search_contract_name || search_contract_code) { //只有一个输入框有值 23 search_contract_name = search_contract_name.length ? search_contract_name : 'xxx'; //默认为xxx是因为不可能存在xxx 24 search_contract_code = search_contract_code.length ? search_contract_code.toLowerCase() : 'xxx'; 25 $("input[name='contract[]']").each( 26 function () { 27 var code_name = this.value; 28 var search_code = code_name.toLowerCase().indexOf(search_contract_code); 29 var search_name = code_name.toLowerCase().indexOf(search_contract_name); 30 if (search_code >=0 || search_name >=0 ) { 31 // this.nextSibling.style.backgroundColor = "#FFDEAD"; 32 this.parentNode.style.display = 'block'; 33 } else { 34 // this.nextSibling.style.backgroundColor = ""; 35 this.parentNode.style.display = 'none'; 36 } 37 } 38 ); 39 } 40 }