jQuery操作下拉框select

获取select值

  • html结构添加select
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>

<body>
    <select id="selector">
        <option value="1">选项一</option>
        <option value="2">选项二</option>
        <option value="3">选项三</option>
        <option value="4">选项四</option>
    </select>
</body>
<script>
</script>

</html>
  • 获取当前选项中的textvalue
 	var text = $("#selector").find("option:selected").text();
    var value = $("#selector").find("option:selected").val();
    console.log("text:" + text);
    console.log("value:" + value);

在这里插入图片描述

  • 获取当前选项中的索引(从0开始)
var index = $("#selector").get(0).selectedIndex;

在这里插入图片描述

  • 获取第一项(最小)和最后一项(最大)的text
	var first = $("#selector option:last").text();
    var last = $("#selector option:first").text();
    console.log("last:" + last);
    console.log("first:" + first);

在这里插入图片描述

更改设置选中状态

  • 改变select的选中,执行该语句后将第1个设置为选中状态,eq(i),i为索引值
    $("#selector").each(function () {
        $(this).find("option").eq(1).prop("selected", true)
    });

在这里插入图片描述

  • 为select添加事件,当选择其中一项时触发事件
	$('#selector').change(function (e) {
        alert("事件触发");
    });

在这里插入图片描述

  • 设置select索引值为2的项选中
$("#selector").get(0).selectedIndex = 2;

在这里插入图片描述

  • 设置select的value值为1的项选中
$("#selector option[value='1']").prop("selected", true);

在这里插入图片描述

添加删除select选项

  • 为select添加一个option下拉项,在末尾添加
$("#selector").append("<option value='5'>选项五</option>");

在这里插入图片描述

  • 为select添加一个option下拉项,在起始位置添加
$("#selector").prepend("<option value='5'>选项五</option>");

在这里插入图片描述

  • 删除select最后一个option
$("#selector option:last").remove();

在这里插入图片描述

  • 删除select中value=3的option
$("#selector option[value='3']").remove();

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

heromps

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值