這裡包括jquery擷取 select項的個數 ,索引 前選中項的文本 選中項的值 text的第一項被選中 刪除select中選定的項 等操作。
//得到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中添加一項,顯示內容為text,值為value,如果該項值已存在,則提示
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;
}