天天看點

jquery插件 - 操作select

     昨天寫了個操作select下拉框的jquery插件,以後再涉及select時,利用這個插件就簡單多了。和大家分享一下代碼:

jquery插件 - 操作select

//得到select項的個數

jQuery.fn.getSize = function()

{

    return jQuery(this).get(0).options.length;

}

//獲得選中項的索引

jQuery.fn.getSelectedIndex = function()

    return jQuery(this).get(0).selectedIndex;

//獲得目前選中項的文本

jQuery.fn.getSelectedText = function()

    if(this.getSize() == 0)

    {

        return "下拉框中無選項";

    }

    else

        var index = this.getSelectedIndex();      

        return jQuery(this).get(0).options[index].text;

//獲得目前選中項的值

jQuery.fn.getSelectedValue = function()

{    

        return "下拉框中無選中值";

        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.getSize();

    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.getSize();    

    if(index >= count || index < 0)

        alert("選中項索引超出範圍");

        jQuery(this).get(0).selectedIndex = index;

//判斷select項中是否存在值為value的項

jQuery.fn.isExistItem = function(value)

        if(jQuery(this).get(0).options[i].value == value)

    return isExist;

//向select中添加一項,顯示内容為text,值為value,如果該項值已存在,則提示

jQuery.fn.addOption = function(text,value)

    if(this.isExistItem(value))

        alert("待添加項的值已存在");

        jQuery(this).get(0).options.add(new Option(text,value));

//删除select中值為value的項,如果該項不存在,則提示

jQuery.fn.removeItem = function(value)

        var count = this.getSize();        

        for(var i=0;i<count;i++)

            if(jQuery(this).get(0).options[i].value == value)

            {

                jQuery(this).get(0).remove(i);

                break;

            }

        }        

        alert("待删除的項不存在!");

//删除select中指定索引的項

jQuery.fn.removeIndex = function(index)

        alert("待删除項索引超出範圍");

        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檔案,再引入jquery.liu.select.js檔案,然後就可調用該插件的方法。比如,我要清除id為selEmail的下拉框中的所有項,那麼我就可以這麼操作:$("#selEmail").clearAll();

   說明:該插件中的方法在ie7和firefox中驗證通過,有錯誤和需要改進的地方還希望大家批評指正。 

   經過使用中,發現size屬性與jquery原本方法沖突,特改成 getSize 。

繼續閱讀