jQuery是控制和操作select详解。

jQuery是控制和操作select详解。 
eg:

<select id="test">
<option value="1">选项一<option>
<option value="2">选项一<option>
                         ...
<option value="n">选项N<option>
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

所谓jQuery操作“select”, 说的更确切一些是应该是jQuery控制 “option”, 看下面的jQuery代码:

//获取第一个option的值

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

//最后一个option的值

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

//获取第二个option的值

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

//获取选中的值

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

//设置值为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());
  • 1
  • 2
  • 3

//获取select的长度

$('#test option').length;
  • 1

//添加一个option

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

//添除选中项

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

//删除项选中(这里删除第一项)

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

//指定值被删除

$('#test option').each(function(){
   if( $(this).val() == '5'){
        $(this).remove();
    }
});
$('#test option[value=5]').remove();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

//获取第一个Group的标签

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

//获取第二group下面第一个option的值

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

//select 默认选中

$("#arrangeClass").find("option[value="+reim.classId+"]").prop("selected",true);

猜你喜欢

转载自blog.csdn.net/thedarkclouds/article/details/81504272