用JS初始化html中的下拉框select

例如有如下的下拉框:

<select class="weather" ></select>

現在對其初始化

 var options=[' ','晴','多雲','小雨','大雪'];
 initselect('weather',options);

對應的JS代碼如下:

//初始化下拉框
function initselect(className,options){
    var sele = document.getElementsByTagName("select");
    var option;
    var value;
    for (var i=0; i<sele.length; i++) {
      if (sele[i].className == className) {
      	 sele[i].innerHTML='';
         value=sele[i].getAttribute("para.value");
         for(var j=0;j<options.length;j++){
            option=document.createElement("option");
            option.value=options[j];
            option.innerHTML=options[j];
            if(value==options[j]){
                option.selected="selected";
            }
            sele[i].appendChild(option);
         }
      }
    }
}

當然,也可以給下拉框設定指定的值,利用虛擬屬性para.value

<select class="weather" para.value="晴" ></select>



發佈了66 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章