Select tag 相關語法

這篇就以看到的例子中相關語法做介紹,

Select options Collection:

擷取重點如下:
The options collection returns a collection of all <option> elements in a drop-down list.

Select add() Method:

擷取重點如下:
add an option to a drop-down list.

Select remove() Method:

擷取重點如下:
remove an option from a drop-down list.



想做的功能: 動態新增下拉選項,

完整code如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<h2>動態新增下拉選項</h2>
<input type="button" value="新增" id="addOptions" data-target="addOptios">
<select id="addOption">
<option value="">請選取</option>
<option value="1">原有選項</option>
</select>

<script>
window.onload = function() {

var _addOptions = document.getElementById("addOptions"),
_addOption = document.getElementById("addOption"),
addOptions = function(target, optons) {                   // target指被新增元素的select; optons指為將新增出的option提供資料的基礎

var _option = null,
ol = optons.length,
i = 0,
_v = "",
_t = "";

for (; i < ol; i++) {

_v = optons[i].value;
_t = optons[i].text;

_option = document.createElement("option");    // 以下4行是新增一個option
_option.value = _v;
_option.text = _t;
target.options.add(_option);               // target.options.add(_option);  --> 也可寫成: target.add(_option);

}

};

_addOptions.onclick = function() {

addOptions(_addOption, [                       // 以陣列包物件方式傳遞資料內容
{
"value": "新增的元素",
"text": "新增的元素"
}
]);

};

};

</script>
</body>
</html>



留言

熱門文章