JS select添加option

<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" onclick="addOption();"/>
<input type="button" value="Remove" onclick="removeOption();"/>
</form>
</body>
</html> 
 

你可能感兴趣的:(JavaScript,json,IE,firefox,Safari)