js中的option

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <!--<input type="button" id = 'seleteSpecific' value='delete'/>-->
    <select><option>smoke bomb</option></select>
</body>
<script type="text/javascript">
//select 元素中的options有自己涂有的方法和属性

//1 新建一个select
    var sel = document.createElement('select');
    sel.id='testSelect';
    document.body.appendChild(sel);

//2 添加option
    var newOption = document.createElement('option');
    newOption.value = 1;
    //newOption.appendChild(document.createTextNode('text'));
    newOption.innerHTML = 'zzz';
    /*if(newOption.innerText){
        alert('NOT FF');
    }else if(newOption.textContent){
        alert('FF');
    }*/
    sel.appendChild(newOption);
    //sel.options.add(new Option('text','1'));
   
//3 删除所有选项   
    //    alert('delete');
    sel.options.length = 0;

//4 删除指定option,先创建几个
    sel.options.add(new Option('text1','1'));
   
    var selectedOption = new Option('text2','2');//创建一个被选中的选项
    //selectedOption.setAttribute('selected','selected');//IE FF 兼容,FF支持new Option('text2','2','selected') 或者 new Option('text2','2',{'selected':'selected'})   
    sel.options.add(selectedOption);
   
    sel.options.add(new Option('text3','3'));

    var anotherSelectedOption = new Option('text4','4');
    anotherSelectedOption.setAttribute('selected','selected');
    sel.options.add(anotherSelectedOption);
   
    //var deletButton = document.getElementById('seleteSpecific');
   
    var index = sel.selectedIndex;
    alert(index);
    //sel.options.remove(index);//options 有自己的remove方法,而一般的DOM只有removeChild方法
    //sel.options[index] = null;

//5 获取选中项的text.option[index]有text属性
    with(sel){//尝试使用with
        //console.log(options);
        alert(options[index].text);
    }

//6 替换选中option
    sel.options[index] = new Option('text5','5');

//删除select,通用其他DOM
    sel.parentNode.removeChild(sel);
</script>
</html>

原文地址:https://www.cnblogs.com/cy056/p/2827025.html