本文主要介绍了jquery实现select下拉框获取当前选中文本、值、索引以及添加/删除select的option项的相关知识,具有很好的参考价值。下面跟着小编一起来看下吧,希望能帮助到大家。
话不多说,请看代码:
//直接保存后缀.htnl用谷歌浏览器打开,亲测有效
<head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function(){
//为select添加事件,当选择其中一项时触发
$("select:eq(0)").change(function(){
//code
});
//获取select选中的text:结果是由所有匹配元素包含的文本内容组合起来的文本
var checktext = $("select:eq(0) :selected").text();//建议用这个简单
= $("select:eq(0) option:selected").tetx();
= $("#one").find(":selected").text();
= $("#one").find("option:selected").text();
//如果多选,将返回一个数组,其包含所选的值。
var checkvalue = $("#select_id").val();
//获取select选中匹配元素的当前值,即[即使多选也只]取得第一个匹配元素的val内容
var checkvalue = $("select:eq(0) :selected").val();//=========强烈建议用这个,以防多选
//获取select选中的索引值
var checkindex = $("#select_id ").get(0).selectedindex;
//获取select最大的索引值
var maxindex = $("#select_id :last").prop("index"); //建议用这个
= $("#select_id option:last").prop("index");
= $("select:eq(0)").find(":last").prop("index")
= $("select:eq(0)").find("option:last").prop("index")
//=========================================================================================
//jquery设置select选择的 text和value:
// 设置select的value值为4的项选中
$("#select_id ").val(4); //用这个
$("#select_id [value='4']").prop("selected", true);
$("#select_id option[value='4']").prop("selected", true);
//设置select中的第一个option被选中
$("select :first").prop("selected", true);//这个
$("select :first").prop("selected", 'selected');
$("select option:first").prop("selected", "true");
$("select option:first").prop("selected", "selected");
//============================================================================================
//jquery添加/删除select的option项
$("#select_id").append("<option value='value'>text</option>"); //为select末尾追加一个option(下拉项)
$("#select_id").prepend("<option value='0'>请选择</option>"); //为select首部插入一个option(第一个位置)
$("#select_id :last").remove(); //删除select中索引值最大option(最后一个)
$("#select_id :fist").remove(); //删除select中索引值最小为0option(第一个)
$("#select_id [value='3']").remove(); //删除select中value='3'的option
});
</script>
</head>
<table>
<tr>
<td>
<!--multiple设定下拉框可以多选,size设定下拉框不呈现下拉方式,-->
<select size="12" id="one" multiple="multiple">
<option value='1'>苹果</option>
<option value="2">香蕉</option>
<option value="3">草莓</option>
<option value="4">橘子</option>
</select>
</td>
<td>
<input type="button" value=">>>"><br>
<input type="button" value=" > "><br>
<input type="button" value=" < "><br>
<input type="button" value="<<<"><br>
</td>
<td>
<select size="12" id="two" multiple="multiple">
<option value="5">葡萄</option>
</select>
</td>
<td>
<input type="button" value=" up "><br><br>
<input type="button" value="down"><br>
</td>
</tr>
</table>
相关推荐:
div+css模拟select下拉框实例代码
html中华支持分类select下拉框的optgroup标签
基于jquery的select下拉框选择触发事件实例分析
以上就是jquery实现select下拉框获取当前选中的文本的详细内容。