获取下拉框选中项(下标,选中项内容)[简单明了,切中要点,多方法,原生、JQ都记上了]

经常用,经常忘记。 

JS

document.querySelector("select").onchange = function(){
	console.log(this.selectedIndex);//选中项下标
	console.log(this.options[this.selectedIndex].innerText);//选中项文本
    console.log(this.options[this.selectedIndex].value);//选中项value
}

JQuery

$("select").change(function(){

	console.log($(this).children("option:selected").text())//选中option标签里的文本值
	console.log($(this).find("option:selected").val())//选中内容

	console.log($(this).children("option:selected").index())//选中下标
	console.log($(this).find("option:selected").index())//选中下标

    console.log($(this).prop("selectedIndex")//选中下标
})

借势科普一下下拉框一些小知识:

1.下拉框长度由最长option决定:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<select name="">
			<option value="1">666</option>
			<option value="2">的法国德国</option>
			<option value="3">是的冯绍峰</option>
			<option value="4">打个梵蒂冈</option>
			<option value="5">额无任何</option>
		</select>
	</body>
</html>

 2.不同品牌的移动端设备下拉框弹出样式不一样:

小米手机:


苹果手机就类似这个,向上划起来:

3.下拉框多选

当select加上multiple属性后, 即可实现多选。

4.下拉框默认选中,提示文字,让提示文字不出现在下拉内容里(即:提示文字不能选中)

当在select的option添加selected属性是 ,就表示默认选中该项;

在单选状态下,若多个option添加selected属性时,显示后一个option内容;

当在select的option添加hidden属性是 ,该项就不会出现在下拉选中;

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="asset/js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<select name="">
			<option value="1">草莓</option>
			<option value="2">苹果</option>
			<option value="3">菠萝</option>
			<option value="4">桃子</option>
			<option selected hidden>请选择你最喜欢的水果</option>
		</select>
		<div class="val"></div>
	</body>
	<script type="text/javascript">
		$("select").change(function(){
			$(".val").text($(this).children("option:selected").text())
		})
	</script>
</html>

猜你喜欢

转载自blog.csdn.net/m0_43599959/article/details/113929026
今日推荐