這裡整理了一些 jQuery 常見的基礎操作,包含去除字串空白、遍歷 checkbox、賦值取值、顯示隱藏以及 radio 按鈕的讀取與設定。
$.trim(" hello, how are you? ");
$("input[type=checkbox][checked]").each(function(){
alert($(this).val());
});
jQuery 中賦值時把值作為參數傳入,與原生 JS 略有不同:
$("#A").val("1"); // 賦值
$("#A").html("1"); $("#A").text("1"); // 設定 HTML / 文本
$("#A").html(); $("#A").text(); // 取值
// 方法一
$('#id').css('display','none');
$('#id').css('display','block');
// 方法二
$('#id').hide();
$('#id').show();
<input type="radio" name="sex" value="Male">Male</input> <input type="radio" name="sex" value="Female">Female</input> <input type="radio" name="sex" value="Unknown">Unknown</input>
取得選中值:
$('input:radio[name=sex]:checked').val();
選擇指定單選鈕:
$('input:radio[name=sex]:nth(0)').attr('checked', true);
// 或
$('input:radio[name=sex]')[0].checked = true;
重置 radio:
$('input:radio[name=sex]').attr('checked', false);
這些都是表單開發中反覆出現的小操作,熟悉後能讓取值、賦值與狀態切換更順手。