以下代碼的測試環境爲:jQuery-2.1.4,IE 11,FireFox 40。
1. text
- 取值與賦值
/* 原生JS */ var txtInput = document.getElementById("txtInput"); var value = txtInput.value; txtInput.value = "new value"; /* jQuery */ var $txtInput = $("#txtInput"); var value = $txtInput.val(); $txtInput.val("new value");
2. checkbox
- 是否選中
/* 原生JS */ var chkInput = document.getElementById("chkInput"); var isChecked = chkInput.checked; //返回boolean /* jQuery */ var $chkInput = $("#chkInput"); //attr只能獲取checkbox初始化時是否選中,選中爲"checked",否則爲undefined var isChecked = $chkInput.attr("checked"); //下面兩種方法都能動態獲取checkbox是否選中,返回boolean isChecked = $chkInput.is(":checked"); isChecked = $chkInput.prop("checked");
- 選中/取消選中
/* 原生JS */ var chkInput = document.getElementById("chkInput"); chkInput.checked = true; /* jQuery */ var $chkInput = $("#chkInput"); $chkInput.attr("checked", true); $chkInput.prop("checked", true);
3. radio
- 選中/取消選中
/* 原生JS */ document.getElementById("radio1").checked = true; /* jQuery */ $("#radio1").attr("checked", true);
- 獲取選中項的值
/* 原生JS */ var radioInputs = document.getElementsByName("radio"); var value; for (var i = 0; i < radioInputs.length; i++) { if (radioInputs[i].checked) { value = radioInputs[i].value; } } /* jQuery */ var $checkedRadio = $("input:radio[name=radio]:checked"); var value = $checkedRadio.val();
4. select
- 獲取選中的值與文本
/* 原生JS */ var selInput = document.getElementById("selInput"); var val = selInput.value; var text = selInput.options[selInput.selectedIndex].text; /* jQuery */ var $selInput = $("#selInput"); var val = $selInput.val(); var text = $("#selInput option:selected").text();
- 通過選項值或者選項文本設置選中/取消選中
/* 原生JS */ var selInput = document.getElementById("selInput"); //選中值爲test的選項 selInput.value = "test"; //選中顯示文本爲test的選項 for (var i = 0; i < selInput.options.length; i++) { //text爲選項的顯示文本,value爲選項的值 if (selInput.options[i].text === "test") { selInput.options[i].selected = true; break; } } /* jQuery */ //選中值爲test的選項 $("#selInput").val("test"); //選中顯示文本爲test的選項 $("#selInput option").filter(function () { return $(this).text() === "test"; }).attr("selected", true);
- 新增/刪除選項
/* 原生JS */ //新增 var selOptions = document.getElementById("selInput").options; var newOption = new Option("testText", "testValue"); selOptions.add(newOption); //刪除 for(var i = 0; i < selOptions.length; i++) { if(selOptions[i].text === "test") { selOptions.remove(i); break; } } /* jQuery */ //新增 var $newOption = $("<option value='testValue'>testText</option>"); $("#selInput").append($newOption); //刪除 $("#selInput option").filter(function() { return $(this).text() === "test"; }).remove();
- 清空選項
/* 原生JS */ document.getElementById("selInput").options.length = 0; /* jQuery */ $("#selInput").empty();