chrysalis 发表于 2013-2-7 19:49:27

[转]巧用sel.options[sel.selectedIndex].text与try{}catch{e}{}操作SELECT选项值

当select.value=value被赋予一个不存在的值时如果在这个时候用sel.options.text来获取当前选择文本会抛出异常。本文主要思想就是catch抛出的异常来断定select中不存在此value的选项,感觉这样做比循环获取每个option的value与新的value值比对是否相等更有效率,废话不多说,上菜!
<html><head><title>JS</title><script type="text/javascript">function $(id)   {       return document.getElementById(id);   }   String.prototype.trim=function()   {       return this.replace(/(^\s*)|(\s*$)/g,"");   }   function init()   {       var originalSel = $("originalSel");      originalSel.options=new Option("text1","1");       originalSel.options=new Option("text2","2");       originalSel.options=new Option("text3","3");       originalSel.options=new Option("text4","4");       originalSel.options=new Option("text5","5");   }   function alertText(){       var value = prompt('请您输入value值','');       if(value==null||value.trim()=="")       {         return;       }         var originalSel = $("originalSel");       originalSel.value=value;       try{         var text = originalSel.options.text;         alert("value="+value+"对应的text是"+text);       }catch(e){         if(originalSel.options)         {               originalSel.options.selected=true;         }         alert("您输入的value不存在!");       }      }   function add()   {       var textValue = prompt("请你输入Text,Value","text,value");       if(textValue==null)       {         alert("请您输入text,value!");         return;       }       var ary = textValue.split(",");       if(ary.length<2||ary.trim()==""||ary.trim()=="")       {         alert("key,value值不能为空!");         return;       }       var text = ary;       var value = ary;       var selObj = $("originalSel");       selObj.value=value;       try{         selObj.options.text;         alert("select中已存在value为"+value+"的选项!");         return;       }catch(e){               selObj.options=new Option(text,value);         selObj.value=value;         alert("增加成功!");       }   }   function remove(){       var value = prompt('请您输入value值','');       if(value==null||value.trim()=="")       {         return;       }       var originalSel = $("originalSel");       originalSel.value=value;       try{         originalSel.options.text;         originalSel.remove(originalSel.selectedIndex);         alert("删除成功!");       }catch(e){         if(originalSel.options)         {               originalSel.options.selected=true;         }         alert("select中不存在value="+value+"的选项!");       }   }   </script>    </head><body ><select id="originalSel" style="width:150px"></select><br><input type="button"value="alertText"><input type="button"value="addOption"><input type="button"value="removeOption"></body></html> 
 
原帖地址:http://ilovejsj.iteye.com/blog/466259
页: [1]
查看完整版本: [转]巧用sel.options[sel.selectedIndex].text与try{}catch{e}{}操作SELECT选项值