jQuery获得select的值及其他操作

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/csdnluolei/article/details/83957949

总结一下 jQuery获得select的值,以及其他操作,

1.获取第一个option的值       

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

2.最后一个option的值                     

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

3.获取第三个option的值          

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

4.获取选中的值value                         

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

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

5.获取选中的值text

$("#test option:selected").text();

获得select所有值text 

$("#test").text();
 

6.设置值为2的option为选中状态   

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


7.获取select的长度            

$('#test option').length;


8.添加一个option

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

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

9.移除选中项       

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

10.指定值被删除

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

(2)$('#test option').each(function(){

   if( $(this).val() == '3'){

        $(this).remove();
    }
});


11.根据option的值选中option

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


12.清空 Select: 

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



猜你喜欢

转载自blog.csdn.net/csdnluolei/article/details/83957949