萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 操作下拉選單、單選、核取方塊完整指南

下拉選單

// 取得選中項文字
var text = $(".formc select[name='country'] option:selected").text();

// 取得選中值
var val = $('.formc select[name="country"]').val();

// 取得選中項 ID
var id = $('.formc select[name="country"]').attr("id");

// 清空選單
$("#select").empty(); // 或 .html('')

// 新增選項
$("<option value='1'>1111</option>").appendTo("#select");

選擇器說明: select[name='country'] option:selected 表示 name 為 country 的 select 內被選中的 option。現代 jQuery 建議用 :selected 而非 [@selected]。

單選按鈕

// 取得選中值
var val = $("input[type=radio][name=xxx]:checked").val();

// 設定 value=2 為選中
$("input[type=radio][value=2]").prop("checked", true);

注意:用 .prop("checked", true) 而非 .attr("checked", "checked"),jQuery 1.6+ 推薦用 prop 操作布林屬性。

核取方塊

// 取得第一個勾選的值
var firstVal = $("input[type=checkbox][name=xxx]:checked").val();

// 遍歷所有勾選項
$("input[type=checkbox][name=xxx]:checked").each(function() {
    alert($(this).val());
});

// 取消勾選
$("#chk1").prop("checked", false);

// 勾選
$("#chk2").prop("checked", true);

// 判斷是否勾選
if ($("#chk1").prop("checked")) { ... }
// 或
if ($("#chk1").is(":checked")) { ... }

版本差異提醒

  • jQuery 1.6 前:.attr("checked") 回傳布林值
  • jQuery 1.6+:.attr("checked") 回傳屬性值("checked" 或 undefined),務必用 .prop("checked") 取得布林狀態
copyright © 萬盛學電腦網 all rights reserved