来自http://tunps.com/javascript-option-value-search-in-select
有个任务,给个公司系统的“人员定岗”加入“人员查找”功能。
这个功能的界面如上图,左边的组织结构树,中间的一个id为left的select是该部门职位下的人员,右边是一个id为right的select,是整个组织的全部人员。可以对left里面的人员进行添加、删除、编辑,这就是“人员定岗”的大致功能。
但是有个缺点,right列表里面的人员多了(比如几千甚至上万)就不好快速的找到需要的人。
所以加入了查找功能。
首先在插入一个文本框和按钮
<input type="text" id="search_input" size="15" value="输入名字查找员工" onFocus="this.value='' " name="B2" /><input type="button" id="search_btn" value=" 查找 " onClick="search()" name="B2" class="btn2" /><br /> |
然后是我写了3个小时的50行js代码加入页面头部的script标签中:
firstTime=1;//第一次点“查询”function search(){ if(firstTime) //如果是第一次点“查询” { //将完整的人员列表每个option的value和text保存在personText,personValue中 var search_input=document.getElementById("search_input").value; var selectedPersonText=new Array(); var selectedPersonValue=new Array(); var l=0; //将查询匹配的人员text,value单独赋值给两个数组 for(var k=0;k<len ;k++) { if(personText[k].indexOf(search_input)>-1) { selectedPersonText[l]=personText[k]; selectedPersonValue[l]=personValue[k]; l++; } } //删掉所有option remove_all(document.getElementById("right")); //显示匹配的option for(l-=1;l>=0;l--) { document.getElementById("right").options.add(new Option(selectedPersonText[l],selectedPersonValue[l])); } firstTime=0;//第一次点“查询”完毕 } else //非第一次“查询” { var search_input=document.getElementById("search_input").value; var selectedPersonText=new Array(); var selectedPersonValue=new Array(); l=0; //将查询匹配的人员text,value单独赋值给两个数组 for(var k=0;k<persontext .length;k++) { if(personText[k].indexOf(search_input)>-1) { selectedPersonText[l]=personText[k]; selectedPersonValue[l]=personValue[k]; l++; } } //删掉所有option remove_all(document.getElementById("right")); //显示匹配的option for(l-=1;l>=0;l--) { document.getElementById("right").options.add(new Option(selectedPersonText[l],selectedPersonValue[l])); } }} |
下面的代码加入页面页脚的script标签中:
var len=document.getElementById("right").options.length;var personText=new Array(len);var personValue=new Array(len); for (var k=0;k<len;k++){ personText[k]=document.getElementById("right").options[k].text; personValue[k]=document.getElementById("right").options[k].value;} |
主要的思路就是:第一次加载页面的时候,从后台数据库把所有员工数据放到了right列表中,输入关键字点查询的时候首先将所有列表项的value和text读入到两个数组中,然后将输入的查询关键字一次和这两个数组用indexOf比较。
indexOf()的作用是查询某字符串是否输入它的一个子字符串,比如不包含返回-1。
然后将查询符合要求的赋值给另外两个数组selectedPersonValue和selectedPersonText,先删除所有列表项,然后将这两个数组用options.add依次添加到列表项中。
当第二次,第三次…点“查询”的时候,就快了,因为直接和内容中的两个数组比较。
1400多个列表项,在IE6下面点“查询” cpu跳到60%~80%,Firefox下面 cpu为30%-40%。可能firefox对js的一些函数有优化吧。
还有一点就是js放的位置也是有讲究的,比如这个例子中,读取right列表长度放在页面页首就不行。因为文档还没有加载晚上,它是识别不出来列表right,回显示"undefined"。
这次修改工作,对js有了近一步了解。我再次感谢firefox的牛逼扩展:firebug,调试js,just easy。
———irrelevant gossip
前天我一同学的公司叫我做网站,是搞教育培训的,比如计算机等级,英语等级等。报价5k8。有个难点就是:在线远程视频培训这块,还有美工的问题,我找了很多同学,同学的同学,都没有牛逼一点的网站美工。唉,看来这笔业务不好接。
