首页 > 技术文章 > jquery操作select的各种方法

lingdublog 2017-03-06 16:21 原文

在工作中,有时候会遇到给select组件添加一些事件,前两天发表了一篇文章,《用jquery给select加选中事件》大致阐述了简单的jq操作select的方法,但是为了详细的介绍一下select,争取让大家把它吃透,也为了和脑残的IE作斗争,于是有了这篇文章的诞生。

一、使用jquery获取select元素(value和option里的内容)

1. var checkText=$("#select_id").find("option:selected").text();  //获取Select选择option里的值Text 
2. var checkValue=$("#select_id").val();  //获取Select选择的Value 

二、使用jquery设置select元素(value和option里的内容)

1. $("#select_id ").get(0).selectedIndex=1;  //设置Select索引值为1的项选中 
2. $("#select_id ").val(2);   // 设置Select的Value值为4的项选中 
3. $("#select_id option[text='aaa']").attr("selected", true);   //设置Select的Text值为aaa的项选中 

三、使用jquery添加删除select元素(option项)

1. $("#select_id").append("<option value='Value'>Text</option>");  //为Select追加一个Option(下拉项) 
2. $("#select_id").prepend("<option value='0'>请选择</option>");  //为Select插入一个Option(第一个位置) 
3. $("#select_id option:last").remove();  //删除Select中索引值最大Option(最后一个) 
4. $("#select_id option[index='0']").remove();  //删除Select中索引值为0的Option(第一个) 
5. $("#select_id option[value='3']").remove();  //删除Select中Value='3'的Option 
6. $("#select_id option[text='4']").remove();  //删除Select中Text='4'的Option 

四、其它的一些常用方法

 清空 Select

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

获取select的最大索引值

 

var maxIndex=$("#select_id option:last").attr("index");  //获取Select最大的索引值 

 

推荐阅读