“ JS中操作<select>标签选的值 ”

发布时间:2022-12-17
今日阅读:0
来源:CSDN
作者:CSND
...

JS中操作标签是一种表单控件,用来创建下拉列表。在标签下的内容,可以通过JS的操作,获取其对象,获取被选项的索引(index)、值(value)、内容(text) img 获取select对象: var myselect=document.getElementById(“selectID”); 其中,selectID标识 想获取的url: myselect.options[index].getAttribute(‘url’); 提示:上面是分步写法,现在看看综合写法 对于上面3的综合写法是: document.getElementById(“selectID”).value; 或 document.getElementById(“selectID”).options[document.getElementById(“selectID”).selectedIndex].value; 对于上面4的综合写法是: document.getElementById(“selectID”).options[document.getElementById(“selectID”).selectedIndex].text 下面给出从下拉列表中选择图片显示的示例源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>演示</title>
    <style>
        div{ 
            margin:20px;
            text-align:center;
        }
    </style>
    <script>
         function show() {
            document.getElementById("imgID").src = document.getElementById("selectID").value;
         }
    </script>
</head>
<body>
    <div > 
        雪景
        <select id="selectID" onchange="show()" style="width:100px;height:30px">
            <option value="./雪1.png">雪1</option>
            <option value="./雪2.png">雪2</option>
            <option value="./雪3.png">雪3</option>
        </select>
        <br>
        <img id="imgID" src="雪1.png" />
    </div>     
</body>
</html>

保存文件名:从下拉列表中选择图片显示1b.html,用浏览器打开效果: img 用JS将数组中的元素信息添加到下拉列表 先介绍将数组的元素信息添加到下拉列表用到的方法和属性 select标签对象的方法 add() 向下拉列表添加一个选项。 语法:selectobject.add(option,before) remove() 从下拉列表中删除一个选项. 语法: selectobject.remove(index) Optiont标签对象的属性 defaultSelected 返回 selected属性的默认值。 index 返回下拉列表中某个选项的索引位置。 Selected 设置或返回 selected 属性的值。 text 设置或返回某个选项的纯文本值。 JS将数组的的元素信息添加到下拉列表,示例源码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>示例</title>
</head>
<body>
    <form name="form1" action="">
        <select name="sel" style="width:100px;height:30px">
        </select><br>
        <input type="button" value="加载数组的数据项" onclick="addopt()">
    </form>
<script>
    var arr=new Array('项1','项2','项3','项4','项5')
    var counts=arr.length;
    function addopt(){
        for(var i=0;i<counts;i++){
            // document.form1.sel.options[i]=new Option (arr[i],i)
            var opt=document.createElement('option')
            opt.text=arr[i]
            opt.value=i;
            document.form1.sel.add(opt,undefined)
        }       
    }
</script>
</body>
</html>

保存文件名:数组的数据项添加到下拉列表.html,用浏览器打开效果: img

标签:
JS select 标签

每日一言

""你的脸,犹如你的人生,一样坎坷。""

...

站点统计

本周更新文章: 0 篇
文章总数: 59110 篇
今日访问量: 35750 次
访问总量: 148200 次