做作業的時候需要給給一個select標籤動態添加option,但卻總是不成功,剛開始我是這樣寫的:
$("#day").options.append(new Option(i,i));
然後發現並沒有變化,查資料後才發現,如果要用jQuery給select標籤動態添加option,需要這樣寫:
$("#day").append("<option value='"+i+"'>"+i+"</option>");
採用上面那種寫法時,應該用var obj=document.getElementById(“day”)來獲取select標籤,完整寫法:
var obj=document.getElementById("day");
obj.options.add(new Option(i,i));
補充一些jQuery對select的操作:
1.清空select中所有選項:$("#id").empty();
2. $("#select_id").prepend(“請選擇”); //爲Select插入一個Option(第一個位置)
3. $("#id option:last").remove(); //刪除Select中索引值最大Option(最後一個)
4. $("#d option[index=‘0’]").remove(); //刪除Select中索引值爲0的Option(第一個)
5. $("#id option[value=‘3’]").remove(); //刪除Select中Value='3’的Option
6. $("#id option[text=‘4’]").remove(); //刪除Select中Text='4’的Option