本節(jié)內(nèi)容:
jquery實(shí)現(xiàn)select下拉框的取值與賦值,設(shè)置選中的方法大全。
比如<select class="selector"></select>
1、設(shè)置value為pxx的項(xiàng)選中
$(".selector").val("pxx");
2、設(shè)置text為pxx的項(xiàng)選中
$(".selector").find("option[text='pxx']").attr("selected",true);
這里有一個(gè)中括號(hào)的用法,中括號(hào)里的等號(hào)的前面是屬性名稱,不用加引號(hào)。
很多時(shí)候,中括號(hào)的運(yùn)用可以使得邏輯變得很簡(jiǎn)單。
3、獲取當(dāng)前選中項(xiàng)的value
$(".selector").val();
4、獲取當(dāng)前選中項(xiàng)的text
$(".selector").find("option:selected").text();
這里用到了冒號(hào),掌握它的用法并舉一反三也會(huì)讓代碼變得簡(jiǎn)潔。
很多時(shí)候用到select的級(jí)聯(lián),即第二個(gè)select的值隨著第一個(gè)select選中的值變化。
這在jquery中是非常簡(jiǎn)單的。
例如:
$(".selector1").change(function(){ // 先清空第二個(gè) $(".selector2").empty(); // 實(shí)際的應(yīng)用中,這里的option一般都是用循環(huán)生成多個(gè)了 var option = $("<option>").val(1).text("pxx"); $(".selector2").append(option); });Js操作Select大全
判斷select選項(xiàng)中 是否存在Value="paraValue"的Item
向select選項(xiàng)中 加入一個(gè)Item
從select選項(xiàng)中 刪除一個(gè)Item
刪除select中選中的項(xiàng)
修改select選項(xiàng)中 value="paraValue"的text為"paraText"
設(shè)置select中text="paraText"的第一個(gè)Item為選中
設(shè)置select中value="paraValue"的Item為選中
得到select的當(dāng)前選中項(xiàng)的value
得到select的當(dāng)前選中項(xiàng)的text
得到select的當(dāng)前選中項(xiàng)的Index
清空select的項(xiàng)
js 代碼
1、判斷select選項(xiàng)中 是否存在Value="paraValue"的Item
function jsSelectIsExitItem(objSelect, objItemValue) { var isExit = false; for (var i = 0; i < objSelect.options.length; i++) { if (objSelect.options[i].value == objItemValue) { isExit = true; break; } } return isExit; }2、向select選項(xiàng)中 加入一個(gè)Item
function jsAddItemToSelect(objSelect, objItemText, objItemValue) { //判斷是否存在 if (jsSelectIsExitItem(objSelect, objItemValue)) { alert("該Item的Value值已經(jīng)存在"); } else { var varItem = new Option(objItemText, objItemValue); objSelect.options.add(varItem); alert("成功加入"); } }3、從select選項(xiàng)中 刪除一個(gè)Item
function jsRemoveItemFromSelect(objSelect, objItemValue) { //判斷是否存在 if (jsSelectIsExitItem(objSelect, objItemValue)) { for (var i = 0; i < objSelect.options.length; i++) { if (objSelect.options[i].value == objItemValue) { objSelect.options.remove(i); break; } } alert("成功刪除"); } else { alert("該select中 不存在該項(xiàng)"); } }4、刪除select中選中的項(xiàng)
新聞熱點(diǎn)
疑難解答
圖片精選