javascript选择框和选择文本的创建与增加以及设置选中项

<script type="text/javascript">
      //得到选中项的索引,文本和值函数
      function getselected(selectedIndex)
      {
        var selectbox=document.forms[0].elements["location"];
        var index=selectbox[selectedIndex];
        var selectedOption=selectbox.options[selectedIndex];
        console.log("索引:"+index.index +" 文本:"+selectedOption.text+" 值:"+selectedOption.value);
      }
      //设置选中项
      function setOpionSelected(index)
      {
        var selectbox=document.forms[0].elements["location"];
        selectbox[index].selected=true;
      }
      setOpionSelected(3);
     //得到选中项的元素
      function getSelectdOptions(selectbox)
      {
        var result=new Array();
        var option=null;
        for(var i=0,len=selectbox.options.length;i<len;i++)
        {
          option=selectbox.options[i];
          if(option.selected)
          {
            result.push(option);
          }
        }
        return result;
      }
      
      var selected=document.forms[0].elements["location"];
      //console.log(getSelectdOptions(selected).pop().index);
      //创建option,这种是用节点的方式
     var newOption=document.createElement("option");
     newOption.appendChild(document.createTextNode("option text"));
     newOption.setAttribute("value","Option value");
     selected.appendChild(newOption);
     //创建option,这种是用option对象创建,再用add()函数添加节点,inserBefore()是选择插入位置,如果是插入到最后第2参数直接用"undefined"即可
  
      var newOption=new Option("option text","option value");
      selected.add(newOption,selected.insertBefore(newOption,selected.options[1]));
     
    </script>

//html部分

<div id="container">
      
        <form action="#" method="post" id="login">
          <select name="location" id="sel">
            <option value="sunnyvale, CA">Sunnyvaleoption>
            <option value="Los Angeles,CA">Los Angelesoption>
            <option value="Mountain View,CA">Mountain Viewoption>
            <option value="">Chinaoption>
            <option >Australiaoption>
          select>
         form>
    div>

你可能感兴趣的:(javascript学习日记,javascript,前端,开发语言)