js动态添加,删除option及add的使用方法
<!DOCTYPE html>
<html>
?? ?<head>
?? ??? ?<meta charset="UTF-8">
?? ??? ?<title>動態建立select及option及add的使用</title>
?? ?</head>
?? ?<body>
?? ?</body>
?? ?<script type="text/javascript">
?? ??? ?//1.創建select
?? ??? ?function createSelect(){
?? ??? ??? ?var mySelect = document.createElement("select");
?? ??? ??? ?mySelect.id = "mySelect";
?? ??? ??? ?document.body.appendChild(mySelect);
?? ??? ?}
?? ??? ?createSelect();
?? ??? ?//2.創建option
?? ??? ?function addOption(){
?? ??? ??? ?//根據id查找對象,
?? ??? ??? ?var obj=document.getElementById('mySelect');
?? ??? ??? ?//添加一個選項
?? ??? ??? ?//方法一:
?? ??? ??? ?obj.add(new Option("文本text1","value值"));
?? ??? ??? ?//或方法二:
?? ??? ??? ?obj.options.add(new Option("文本text2","value值"));
?? ??? ?}
?? ??? ?addOption();
?? ??? ?
//?? ??? ?3.刪除所有選項option ?? ?
?? ??? ?function removeAll(){
?? ??? ??? ?var obj=document.getElementById('mySelect');
?? ??? ??? ?obj.options.length=0;
?? ??? ?}
//?? ??? ?removeAll();?? ?
//?? ??? ?4.刪除一個選項option
?? ??? ?function removeOne(){
?? ??? ??? ?var obj=document.getElementById('mySelect');
?? ??? ??? ?//index,要刪除選項的序號,這里取當前選中選項的序號
?? ??? ??? ?var index=obj.selectedIndex;
?? ??? ??? ?console.log(index)
?? ??? ??? ?obj.options.remove(index);
?? ??? ?}
?? ??? ?removeOne();
//?? ??? ?5.獲得選項option的值
?? ??? ?var obj=document.getElementById('mySelect');
?? ??? ?var index=obj.selectedIndex; //序號,取當前選中選項的序號
?? ??? ?var val = obj.options[index].value;
?? ??? ?console.log(val)
//?? ??? ?6.獲得選項option的文本
?? ??? ?var obj=document.getElementById('mySelect');
?? ??? ?var index=obj.selectedIndex; //序號,取當前選中選項的序號
?? ??? ?var val2 = obj.options[index].text;
//?? ??? ?7.7.修改選項option
?? ??? ?var obj=document.getElementById('mySelect');
?? ??? ?var index=obj.selectedIndex; //序號,取當前選中選項的序號
?? ??? ?var val3 = obj.options[index]=new Option("新文本","新值");
//?? ??? ?8.刪除select
?? ??? ?function removeSelect(){
?? ??? ??? ?var mySelect = document.getElementById("mySelect");
?? ??? ??? ?mySelect.parentNode.removeChild(mySelect);
?? ??? ?}
?? ??? ?????
?? ?</script>
</html>
轉載于:https://www.cnblogs.com/gshufan/p/6171129.html
總結
以上是生活随笔為你收集整理的js动态添加,删除option及add的使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阶段二总结
- 下一篇: ViewPager图片切换的简单案例