<html>
<head>
<script language="javascript">
var json = {a:'A',b:'B'};
function addOption(){
var select = document.getElementById("mySelect");
//方法一
var option1 = new Option(json.a,'a');
select.options.add(option1);
//方法二
var option2 = document.createElement("option");
option2.value = 'b';
option2.innerText = json.b;
if (browserType() == 'FF') option2.text = json.b;
select.appendChild(option2);
}
function removeOption(){
var select = document.getElementById("mySelect");
//方法一(全部删除)
//select.length = 0;
//方法二(全部删除)
//select.options.length = 0;
//方法三(单个删除)
while(select.options.length > 0) {
if (browserType() == 'IE') {
select.options.remove(select.options.length - 1);
} else if (browserType() == 'FF') {
select.removeChild(select.options[select.options.length - 1]);
}
}
}
function browserType() {
if (navigator.userAgent.indexOf("MSIE") > 0) {
return 'IE';
} else if (navigator.userAgent.indexOf("Firefox") > 0) {
return 'FF';
} else if (navigator.userAgent.indexOf("Safari") > 0) {
return 'SF';
}
}
</script>
</head>
<body>
<form name="myForm">
<select name="mySelect" id="mySelect">
</select><br/>
<input type="button" value="Add" οnclick="addOption();"/>
<input type="button" value="Remove" οnclick="removeOption();"/>
</form>
</body>
</html>
JS select添加option
最新推荐文章于 2023-11-30 20:21:41 发布