首頁 >web前端 >js教程 >詳解select標籤設定預設選取的方法

詳解select標籤設定預設選取的方法

小云云
小云云原創
2018-03-03 09:12:082321瀏覽

本文主要為大家分享一篇select標籤設定預設選取的選項方法,具有很好的參考價值,希望能幫助大家。

方法有兩種。

第一種 透過

1 option >
2 option >
3 option >
 select >

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

function change(){
  document.getElementById("sel")[2].selected=true;
}
 script >

1 option >
2 option >
3 option >
 select >

取得

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);
}

相關推薦:

#在HTML裡select標籤有哪些用法

JQuery 取得多個select標籤option的text內容(實例)

#js取得select標籤value值的方法詳解

#

以上是詳解select標籤設定預設選取的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn