首頁  >  文章  >  web前端  >  html中關於標籤如何設定預設選取的選項詳解

黄舟
黄舟原創
2017-07-28 09:18:473379瀏覽

方法有兩種。

第一種透過221f08282418e2996498697df914ce4e的屬性來設定選取項,此方法可以在動態語言如php在後台根據需要控制輸出結果。

< select  id =  "sel" >
< option  value = "1" >1</ option >
< option  value = "2"  selected = "selected" >2</ option >
< option  value = "3" >3</ option >
</ select >


第二種為透過前端js來控制選取的項目:

< script  type = "text/javascript" >
function change(){
     document.getElementById("sel")[2].selected=true;
}
</ script >
< select  id =  "sel" >
< option  value = "1" >1</ option >
< option  value = "2" >2</ option >
< option  value = "3" >3</ option >
</ select >
< input  type = "button"  value = "修改"  onclick = "change()"  />

取得221f08282418e2996498697df914ce4e標籤選取項目文字的js程式碼為:

var  val = document.all.Item.options[document.all.Item.selectedIndex].text
var  i=document.getElementById( &#39;sel&#39; ).options[document.getElementById( &#39;sel&#39; ).selectedIndex].value;

一些其它操作221f08282418e2996498697df914ce4e標籤的技巧如下:

#1)動態建立select

function  createSelect(){
var  mySelect = document.createElement( "select" );
mySelect.id =  "mySelect" ;
document.body.appendChild(mySelect);
}

2)新增選項option

#
function  addOption(){
//根据id查找对象,
var  obj=document.getElementById( &#39;mySelect&#39; );
//添加一个选项
obj.add( new  Option( "文本" , "值" ));
}

3)刪除所有選項option

function  removeAll(){
var  obj=document.getElementById( &#39;mySelect&#39; );
obj.options.length=0;
}

4)刪除一個選項option

function  removeOne(){
var  obj=document.getElementById( &#39;mySelect&#39; );
//index,要删除选项的序号,这里取当前选中选项的序号
var  index=obj.selectedIndex;
obj.options.remove(index);
}

5)取得選項option的值

var  obj=document.getElementById( &#39;mySelect&#39; );
var  index=obj.selectedIndex;  //序号,取当前选中选项的序号
var  val = obj.options[index].value;

6)取得選項option的文字

var  obj=document.getElementById( &#39;mySelect&#39; );
var  index=obj.selectedIndex;  //序号,取当前选中选项的序号
var  val = obj.options[index].text;

7)修改選項option

var  obj=document.getElementById( &#39;mySelect&#39; );
var  index=obj.selectedIndex;  //序号,取当前选中选项的序号
var  val = obj.options[index]= new  Option( "新文本" , "新值" );

8)刪除select

function  removeSelect(){
var  mySelect = document.getElementById( "mySelect" );
mySelect.parentNode.removeChild(mySelect);
}

以上是html中關於