Javascript与jQuery操作<select/>

本文介绍如何使用JavaScript和jQuery操作HTML中的Select元素,包括获取选中项的文本与值、选中指定项、增加和删除选项等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTML中<select/>元素如下:

<select id="select">
    <option value="opt1">Option1</option>
    <option value="opt2">Option2</option>
    <option value="opt3">Option3</option>
</select>

 

1. 获取选中向项的文本与值:

var selectEle = document.getElementById("select");
var selectedOption = selectEle.options[selectEle.selectedIndex];
var selectedText = selectedOption.text;
var selectedVal = selectedOption.value;

   或者使用jQuery

var $selectedOpt = $("#select").find("option:selected");
var selectedText = $selectedOpt.text();
var selectedVal = $selectedOpt.val();

 2.选中某一项(3种方式)

//1.设置选项的selected属性选中
var selectEle = document.getElementById("select");
selectEle.options[2].selected = true;

//2.通过select元素的selectedIndex属性选中
document.getElementById("select").selectedIndex = 2;

//3.通过设置select元素的值匹配选项
document.getElementById("select").value = "opt3";

 或者使用jQuery

//1.设置选项的selected属性选中
$("#select option[value='opt3']").attr("selected", true);

//2.通过设置select元素的值匹配选项
$("#select").val("opt3");

 3.增加一个选项

var selectEle = document.getElementById("select");
var newOpt = new Option("Option4", "opt4");
selectEle.options.add(newOpt);

 或者使用jQuery

var $newOpt = $("<option value='opt4'>Option4</option>");
$("#select").append($newOpt);

 4.删除一个选项

var selectEle = document.getElementById("select");
selectEle.options.remove(selectEle.selectedIndex);

  或者使用jQuery

$("#select option:selected").remove();

 5.清空所有选项

document.getElementById("select").options.length = 0;

  或者使用jQuery

$("#select").empty();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值