随笔 - 113  文章 - 0  评论 - 85  阅读 - 54万

jQuery获取option的一些常用方法

转发地址:https://www.cnblogs.com/yuanlaihenkuang/p/7171356.html

jQuery的一些方法理出一些常用的方法:

//获取第一个option的值 
$('#test option:first').val(); 
//最后一个option的值 
$('#test option:last').val(); 
//获取第二个option的值 
$('#test option:eq(1)').val(); 
//获取选中的值 
$('#test').val(); 
$('#test option:selected').val(); 
//设置值为2的option为选中状态 
$('#test').attr('value','2'); 
//设置第一个option为选中 
$('#test option:last').attr('selected','selected'); 
$("#test").attr('value' , $('#test option:last').val()); 
$("#test").attr('value' , $('#test option').eq($('#test option').length - 1).val()); 
//获取select的长度 
$('#test option').length; 
//添加一个option 
$("#test").append("ff"); 
$("ff").appendTo("#test"); 
//添除选中项 
$('#test option:selected').remove(); 
//指定项选中 
$('#test option:first').remove(); 
//指定值被删除 
$('#test option').each(function(){ 
if( $(this).val() == '5'){ 
$(this).remove(); 

}); 
$('#test option[value=5]').remove(); 

//获取第一个Group的标签 
$('#test optgroup:eq(0)').attr('label'); 
//获取第二group下面第一个option的值 
$('#test optgroup:eq(1) :option:eq(0)').val(); 

获取select中选择的text与value相关的值 

获取select选择的Text : var checkText=$("#slc1").find("option:selected").text(); 
获取select选择的value:var checkValue=$("#slc1").val(); 
获取select选择的索引值: var checkIndex=$("#slc1 ").get(0).selectedIndex; 
获取select最大的索引值: var maxIndex=$("#slc1 option:last").attr("index"); 

设置select选择的Text和Value 

设置select索引值为1的项选中:$("#slc1 ").get(0).selectedIndex=1; 
设置select的value值为4的项选中: $("#slc1 ").val(4); 
设置select的Text值为JQuery的选中: 
$("#slc1 option[text='jQuery']").attr("selected", true); 
PS:特别要注意一下第三项的使用哦。看看JQuery的选择器功能是如此地强大呀! 

添加删除option项 

为select追加一个Option(下拉项) 
$("#slc2").append(""+i+""); 
为select插入一个option(第一个位置) 
$("#slc2").prepend("请选择"); 
PS: prepend 这是向所有匹配元素内部的开始处插入内容的最佳方式。 
删除select中索引值最大option(最后一个) 
$("#slc2 option:last").remove(); 
删除select中索引值为0的option(第一个) 
$("#slc2 option[index='0']").remove(); 
删除select中value='3'的option 
$("#slc2 option[value='3']").remove(); 
删除select中text='4'的option 
$("#slc2 option[text='3']").remove();

posted on   林枫山  阅读(184)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2010-08-05 启动Sql身份验证模式/Sa登录
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示