使用jquery操作select(获取选中option的值等)

总结下使用jQuery操作select的方法。

1.获取第一个候选项的值。

$('#test option:first').val();

2.获取最后一个候选项的值。

$('#test option:last').val();

3.获取第二个候选项的值。

$('#test option:eq(1)').val();

4.获取选中的候选项的值。

$('#test').val();

$('#test option:selected').val();

5.设置值为2的候选项为选中状态。

$('#test').attr('value','2');

6.设置最后一个候选项为选中。

$('#test option:last').attr('selected','selected');

$("#test").attr('value' , $('#test option:last').val());

$("#test").attr('value' , $('#test option').eq($('#test option').length - 1).val());

7.获取候选项列表的长度。

$('#test option').length;

8.添加一个候选项。

$("#test").append("<option value='n+1'>第N+1项</option>");

$("<option value='n+1'>第N+1项</option>").appendTo("#test");

9.删除选中项。

$('#test option:selected').remove();

10.删除项(这里删除第一项)。

$('#test option:first').remove();

11.删除指定值。

$('#test option').each(function() {
   if ($(this).val() == '5'){
        $(this).remove();
    }
});

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

12.获取第一个分组的标签。

$('#test optgroup:eq(0)').attr('label');

13.获取第二个分组下面第一个候选项的值。

$('#test optgroup:eq(1) : option:eq(0)').val();

14.根据候选项的值选中候选项。

$("#sel option:contains('C')").prop("selected", true);

select在业务表单中使用得非常多,掌握如何使用jQuery去操作select是很有必要的,即使现在的前端发展趋势是提倡操作数据而避免直接操作dom(比如vue)。

"记忆总是这样不经意间窜入脑海,我终于没能留下你渐行渐远的脚步。"

猜你喜欢

转载自www.cnblogs.com/yanggb/p/12857528.html