您好,欢迎访问一九零五行业门户网

javascript如何取option的text值(firefox下使用)

javascript如何取option的text值(firefox下使用)
firefox下面没有innertext,所以我们想在firefox下获取下列框选中option的text(注意不是value)时会比较吃力。笔者结合自己在项目中的解决方案和代码总结一下,请大家指教。
知识点:
0、为什么要innertext?因为安全问题
1、为firefox dom模型扩展属性
2、currentstyle属性可以取得实际的style状态
3、ie实现innertext时考虑了display方式,如果是block则加换行
4、为什么不用textcontent?因为textcontent没有考虑元素的display方式,所以不完全与ie兼容
代码: 在ie6,7,8 和firefox 2,3下测试均通过。
<html> <head> <script language="javascript"> //if your browser is ie , return true. if is others, like firefox, return false. function isie(){ //ie? if (window.navigator.useragent.tolowercase().indexof("msie")>=1) return true; else return false; } //if is firefox , we need to rewrite its innertext attribute. if(!isie()){ //firefox innertext define htmlelement.prototype.__definegetter__( "innertext", function(){ var anystring = ""; var childs = this.childnodes; for(var i=0; i<childs.length; i++) { if(childs[i].nodetype==1) anystring += childs[i].tagname=="br" ? '\n' : childs[i].textcontent; else if(childs[i].nodetype==3) anystring += childs[i].nodevalue; } return anystring; } ); htmlelement.prototype.__definesetter__( "innertext", function(stext){ this.textcontent=stext; } ); } function getselectedtext(name){ var obj=document.getelementbyid(name); for(i=0;i<obj.length;i++){ if(obj[i].selected==true){ return obj[i].innertext; } } } function chk(){ var objtext = getselectedtext("myselect"); alert("seleted option's text is : "+objtext); var objvalue=document.getelementbyid("myselect").value; alert("seleted option's value is :"+objvalue); } </script> </head> <body> <select id="myselect"> <option value="1111">my 1111 hahaha</option> <option value="2222">my 2222</option> <option value="3333">my 3333</option> <option value="4444">my 4444</option> </select> <input type="button" name="button" value="see result" onclick="javascript:chk();"> </body> </html>
当然,如果单独针对下拉框,也可以不用重写innertext,用下面的代码也能实现。重写innertext是为了兼容除下拉框以外的其他的html 元素。
<html> <head> <script language="javascript"> function chk(){ //var objtext = getselectedtext("myselect"); var obj = document.getelementbyid("myselect"); var objtext = obj.options[obj.selectedindex].text alert("seleted option's text is : "+objtext); var objvalue=document.getelementbyid("myselect").value; alert("seleted option's value is :"+objvalue); } </script> </head> <body> <select id="myselect"> <option value="1111">my 1111 hahaha</option> <option value="2222">my 2222</option> <option value="3333">my 3333</option> <option value="4444">my 4444</option> </select> <input type="button" name="button" value="see result" onclick="javascript:chk();"> </body> </html>
以上就是javascript如何取option的text值(firefox下使用)的内容。
其它类似信息

推荐信息