jQuery之checkbox|radio|select操作
jQuery1.6中添加了prop方法,看起来和用起来都和attr方法一样,但是在一些特殊情况下,attribute和properties的区别非常大,在jQuery1.6之前,.attr()方法在获取一些attributes的时候使用了property值,这样会导致一些不一致的行为。在jQuery1.6中,.prop()方法提供了一中明确的获取property值得方式,这样.attr()方法仅返回attributes。 –摘自jQuery API文档
checkbox
1 2 3
| <input type='checkbox' value='1'/> <input type='checkbox' value='2'/> <input type='checkbox' value='3'/>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| $("input[type=checkbox]") $("input[type=checkbox]:checked") $("input[type=checkbox]:not(:checked)") $("input[type=checkbox]").not(":checked")
$("input[type=checkbox]:first")
$("input[type=checkbox]:checked").length
$("input[type=checkbox]:first").prop("checked") $("input[type=checkbox]:first").prop("checkbox",true)
$("input[type=checkbox]:not(:checked)").prop("checked",true) $("input[type=checkbox]:checkbox").prop("checked",false)
$("input[type=checkbox]").each(function(){ if($(this).prop("checked")){ $(this).prop("checked",false); }else{ $(this).prop("checked",true); } })
|
radio
1 2 3
| <input type='radio' name='rank' value='1' /> <input type='radio' name='rank' value='2' /> <input type='radio' name='rank' value='3' />
|
1 2 3 4 5 6 7 8
| $("input[type=radio]") $("input[type=radio]:checked") $("input[type=radio]:not(:checkbox)")
$("input[type=radio]:checked").val()
$("input[type=radio]:first").prop("checked") $("input[type=radio]:first").prop("checked",true)
|
select
1 2 3 4 5 6
| <select> <option value='1'>1</option> <option value='2'>2</option> <option value='4'>3</option> </select>
|
1 2 3 4 5 6 7 8
| $("select option:selected") $("select").val() $("select option:selected").text()
$("select option:first").prop("selected") $("select option:first").prop("selected",true) $("select option:selected").prop("selected",false)
|