ホームページ  >  記事  >  ウェブフロントエンド  >  jqueryの操作Selectはjsプラグインで扱えるので簡単便利です。

jqueryの操作Selectはjsプラグインで扱えるので簡単便利です。

WBOY
WBOYオリジナル
2016-05-16 18:41:47897ブラウズ

js コードは次のとおりです:

コードをコピー コードは次のとおりです:

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;
{
varindex = 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 の値
jQuery.fn.setSelectedValue = function(value)
{
jQuery(this).get(0).value = value;
}
//Set選択されるテキストを持つ最初の項目
jQuery .fn.setSelectedText = function(text)
{
var isExist = false;
var count = this.size(); for(var i=0;i{
if(jQuery(this).get(0).options[i].text == text)
{
jQuery (this).get(0).options[i]. selected = true;
isExist = true;
}
}
if(!isExist);
alert("ドロップダウン ボックスに項目がありません" );
}
}
//選択したインデックス項目を設定します
jQuery.fn.setSelectedIndex = function(index )
{
var count = this.size();
if(index >= count || index {
alert("選択されたアイテムのインデックスが不足していますof range");
}
else
{
jQuery (this).get(0).selectedIndex =index;
}
}
// あるかどうかを判断しますselect item
jQuery.fn.isExistItem = function(value)
{
var isExist = false;
var count = this.size(); の項目です。 (var i=0;i{
if(jQuery (this).get(0).options[i].value == value)
{
isExist = true;
break;
}
return isExist;
}
// 表示内容がテキストで、値が 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{
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.
if(index >= count | |index
{
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 を導入します。
次にこれをインポートします。 js ファイルを開くと、次のメソッドを使用できます。
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。