Radio 操作
<input type="radio" name="rd" id="rd1" checked value="rd1">
<input type="radio" name="rd" id="rd2" value="rd2">
<input type="radio" name="rd" id="rd3" value="rd3">
- 獲取選中值:
$('input:radio:checked').val() / $("input[name='rd']:checked").val()
- 選中第一個:
$('input:radio:first').prop('checked', true)
- 選中最後:
$('input:radio:last').prop('checked', true)
- 按索引選中:
$('input:radio').eq(index).prop('checked', true)
- 按值選中:
$("input:radio[value='rd2']").prop('checked', true)
- 刪除:
$("input:radio[value='rd2']").remove() / .eq(index).remove()
- 遍歷:
$('input:radio').each(function(i, el){ ... })
Select (DropDownList) 操作
<select id="sel">
<option value="1" selected>a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
- 獲取選中 Value:
$('#sel').val()(最簡)或 $('#sel option:selected').val()
- 獲取選中 Text:
$('#sel option:selected').text()
- 獲取選中索引:
$('#sel')[0].selectedIndex
- 獲取長度:
$('#sel')[0].options.length
- 設置選中:
$('#sel').val('2') 或 $('#sel')[0].selectedIndex = 1
- 添加選項:
$('#sel').append('')
- 刪除選項:
$('#sel option:last').remove() / $('#sel option[value="2"]').remove()
- 清空:
$('#sel').empty()
Checkbox 操作
- 全選/反選:
$('#checkAll').click(function(){ $('input:checkbox').prop('checked', this.checked); })
- 獲取所有勾選值:
$.map($('input:checkbox:checked'), function(el){ return el.value; })
最佳實踐
- 優先使用
.prop() 而非 .attr() 操作 checked/disabled/selected 等布爾屬性(jQuery 1.6+)。
- 使用
.val() 統一獲取/設置表單值,簡潔跨控件。