當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript操作select控件
生活随笔
收集整理的這篇文章主要介紹了
JavaScript操作select控件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<html lang="en">
<head><meta charset="UTF-8"><title>Select控件測試</title>
</head>
<body><select id="mySel"></select><input type="text" id="id" placeholder="請輸入要移除的ID號碼"><hr/><button id="btn1" type="button" >初始化數據</button><button id="btn2" type="button" >測試移除操作</button><button id="btn3" type="button" >測試移除選中的項目</button><button id="btn4" type="button" >修改選中項目的顯示名稱</button><button id="btn5" type="button" >設置1002選擇狀態</button><button id="btn6" type="button" >獲取當前項目的文字,屬性,索引</button><button id="btn7" type="button" >清空列表</button><script type="text/javascript">window.onload=function () {var objSelect = document.getElementById("mySel");document.getElementById("btn1").onclick=function () {//獲取option的長度var length = objSelect.options.length;if(length==0){alert("沒有內容,添加默認內容");//使用innerHTML操作,方式一objSelect.innerHTML="<option value=''>請選擇你的部門</option>";//設置按鈕為可用this.disabled=false;}else{//設置按鈕為不可用this.disabled=true;//使用本地對象添加數據,方式二var valItem = new Option("測試部","1001");//添加操作objSelect.options.add(valItem);var valItem = new Option("軟件部","1002");//添加操作objSelect.options.add(valItem);var valItem = new Option("研發部","1003");//添加操作objSelect.options.add(valItem);}}document.getElementById("btn2").onclick=function () {//獲取輸入的ID號碼var id = document.getElementById("id").value;var length = objSelect.options.length;//判斷if(length>0){//迭代for(var i = 0 ;i<length;i++){if(objSelect.options[i].value==id){//移除操作,方式一objSelect.options.remove(i);break;//跳出循環}}}else{alert("沒有項目,空白的!");document.getElementById("btn1").disabled=false;}}document.getElementById("btn3").onclick=function () {var length = objSelect.options.length;for(var i = 0 ;i<length;i++){if(objSelect.options[i].selected){//移除操作,方式二objSelect.options[i]=null;break;//跳出循環}}}document.getElementById("btn4").onclick=function () {//設置兩個簡單變量,不弄復雜化的操作了var oValue = 1001;//修改內容var modText = "修改為胖先森";var modValue = 101;var length = objSelect.options.length;for(var i = 0 ;i<length;i++){if(objSelect.options[i].value==oValue){objSelect.options[i].text=modText;objSelect.options[i].value=modValue;break;//跳出循環}}}document.getElementById("btn5").onclick=function () {//方式一:推薦方式objSelect.value=1002;//方式二/*var length = objSelect.options.length;for(var i = 0 ;i<length;i++){if(objSelect.options[i].value==1002){objSelect.options[i].selected=true;break;//跳出循環}}*/}document.getElementById("btn6").onclick=function () {alert("當前的索引:"+objSelect.selectedIndex);alert("當前的文字:"+objSelect.options[objSelect.selectedIndex].text);alert("當前值,方式一:"+objSelect.options[objSelect.selectedIndex].value);alert("當前值,推薦方式二:"+objSelect.value);}document.getElementById("btn7").onclick=function () {//不使用DOM操作,清空objSelect.options.length=0;document.getElementById("btn1").disabled=false;}}</script></body>
</html>復制代碼
總結
以上是生活随笔為你收集整理的JavaScript操作select控件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML meta标签总结与属性使用介绍
- 下一篇: cassandra集群搭建