HTML中的標籤如何設置默認選中的選項

方法有兩種。

第一種通過的屬性來設置選中項,此方法可以在動態語言如php在後臺根據需要控制輸出結果。

< select id = “sel” >
< option value = “1” >1
< option value = “2” selected = “selected” >2
< option value = “3” >3

第二種爲通過前端js來控制選中的項:

< script type = “text/javascript” >
function change(){
document.getElementById(“sel”)[2].selected=true;
}

< select id = “sel” >
< option value = “1” >1
< option value = “2” >2
< option value = “3” >3

< input type = “button” value = “修改” onclick = “change()” />

獲取標籤選中項文本的js代碼爲:
var val = document.all.Item.options[document.all.Item.selectedIndex].text
var i=document.getElementById(‘sel’).options[document.getElementById( ‘sel’ ).selectedIndex].value;

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

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( ‘mySelect’ );
//添加一個選項
obj.add( new Option( “文本” , “值” ));
}

3)刪除所有選項option
function removeAll(){
var obj=document.getElementById( ‘mySelect’ );
obj.options.length=0;
}

4)刪除一個選項option
function removeOne(){
var obj=document.getElementById( ‘mySelect’ );
//index,要刪除選項的序號,這裏取當前選中選項的序號
var index=obj.selectedIndex;
obj.options.remove(index);
}

5)獲得選項option的值
var obj=document.getElementById( ‘mySelect’ );
var index=obj.selectedIndex; //序號,取當前選中選項的序號
var val = obj.options[index].value;

6)獲得選項option的文本
var obj=document.getElementById( ‘mySelect’ );
var index=obj.selectedIndex; //序號,取當前選中選項的序號
var val = obj.options[index].text;

7)修改選項option
var obj=document.getElementById( ‘mySelect’ );
var index=obj.selectedIndex; //序號,取當前選中選項的序號
var val = obj.options[index]= new Option( “新文本” , “新值” );

8)刪除select
function removeSelect(){
var mySelect = document.getElementById( “mySelect” );
mySelect.parentNode.removeChild(mySelect);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章