select 如何在选中后获取选中的时是什么元素 ,(原生js)

时间:2023-03-09 22:58:05
select 如何在选中后获取选中的时是什么元素 ,(原生js)

在日常开发中,我们经常遇到选择框的业务处理:如何去获取我们所选中的数据呢? 很多小伙伴还不是很熟悉!

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head> <body> <!-- 原生方式获取被选中的值 -->
<select id="select">
<option >北京</option>
<option >上海</option>
<option >深圳</option>
<option >广州</option>
</select>
<script>
// console.log(select)
select.onchange = function(){
alert(this.value)
}
</script> </body> </html>

很多小伙伴还在用原生的js 去操作option的点击事件,然而这种做法是不对的呢!!!要获取选中的数据,我们用的是操作select 。使用onchange 事件就可以拿到我们想要的数据了,

这样是不是很方便呢?