下拉框(select)的操作在日常開發中非常頻繁。這裡分享一套自己封裝的 jQuery 插件,把取得選中項、添加刪除選項、清空列表等常用操作都封裝成方法,讓 select 的操作更簡潔直觀。
以下是完整的 JavaScript 代碼:
代碼如下:
//得到select項的個數
jQuery.fn.size = function(){ return jQuery(this).get(0).options.length; }
//獲得選中項的索引
jQuery.fn.getSelectedIndex = function(){ return jQuery(this).get(0).selectedIndex; }
//獲得當前選中項的文本
jQuery.fn.getSelectedText = function(){
if(this.size() == 0){ return "下拉框中無選項"; }
else{ var index = this.getSelectedIndex(); return jQuery(this).get(0).options[index].text; }
}
//獲得當前選中項的值
jQuery.fn.getSelectedValue = function(){
if(this.size() == 0){ return "下拉框中無選中值"; }
else{ return jQuery(this).val(); }
}
//設置select中值為value的項為選中
jQuery.fn.setSelectedValue = function(value){ jQuery(this).get(0).value = value; }
//設置select中文本為text的第一項被選中
jQuery.fn.setSelectedText = function(text){
var isExist = false;
var count = this.size();
for(var i=0;i<count;i++){
if(jQuery(this).get(0).options[i].text == text){ jQuery(this).get(0).options[i].selected = true; isExist = true; break; }
}
if(!isExist){ alert("下拉框中不存在該項"); }
}
//設置選中指定索引項
jQuery.fn.setSelectedIndex = function(index){
var count = this.size();
if(index >= count || index < 0){ alert("選中項索引超出范圍"); }
else{ jQuery(this).get(0).selectedIndex = index; }
}
//判斷select項中是否存在值為value的項
jQuery.fn.isExistItem = function(value){
var isExist = false;
var count = this.size();
for(var i=0;i<count;i++){
if(jQuery(this).get(0).options[i].value == value){ isExist = true; break; }
}
return isExist;
}
//向select中添加一項
jQuery.fn.addOption = function(text,value){
if(this.isExistItem(value)){ alert("待添加項的值已存在"); }
else{ jQuery(this).get(0).options.add(new Option(text,value)); }
}
//刪除select中值為value的項
jQuery.fn.removeItem = function(value){
if(this.isExistItem(value)){
var count = this.size();
for(var i=0;i<count;i++){
if(jQuery(this).get(0).options[i].value == value){ jQuery(this).get(0).remove(i); break; }
}
}
else{ alert("待刪除的項不存在!"); }
}
//刪除select中指定索引的項
jQuery.fn.removeIndex = function(index){
var count = this.size();
if(index >= count || index < 0){ alert("待刪除項索引超出范圍"); }
else{ jQuery(this).get(0).remove(index); }
}
//刪除select中選定的項
jQuery.fn.removeSelected = function(){
var index = this.getSelectedIndex();
this.removeIndex(index);
}
//清除select中的所有項
jQuery.fn.clearAll = function(){ jQuery(this).get(0).options.length = 0; }
使用時,先引入 jquery.js,再引入這個插件檔,之後就能直接調用。例如要清除 id 為 selEmail 的下拉框中的所有項,只需寫 $("#selEmail").clearAll(); 即可。
這套插件把繁瑣的 select 操作都做了合理的封裝與邊界判斷(如索引越界、選項是否存在),並已在 IE7 與 Firefox 中驗證通過,很適合作為實際專案的工具函式庫。