9

特定のクラス名を持つすべてのドロップダウン選択をループしてアイテムを追加したいのですが、正しいセレクターで苦労しています


編集: 賛成された受け入れられた答えのほとんどが機能していないように見えるので、私は何か間違ったことをしているに違いありません。以下のHTMLとjqueryコードの両方を貼り付けました。これが理にかなっている場合はお知らせください。


HTML:

<select onfocus="this.enteredText='';" onkeydown="return handleKey();" onkeyup="event.cancelbubble=true;return false;" onkeypress = "return selectItem();"  class="componentSelect"  id="components0" name="applicationUpdater.dependencies[0].componentName" >
<option value= 5 >Client</option>
<option value= 79 >Server</option>
</select>

 <select onfocus="this.enteredText='';" onkeydown="return handleKey();" onkeyup="event.cancelbubble=true;return false;" onkeypress = "return selectItem();"  class="componentSelect"  id="components1" name="applicationUpdater.dependencies[0].componentName" >
<option value= 5 >Client</option>
<option value= 79 >Server</option>
</select>

など。。。

jqueryコード:

    $('select.componentSelect').each(function() {
        var select = $(this);
        $(select).children('option').each(function() {
            if ($(this).text() == currentComponentName) {
                $(this).remove();
            }
        });

    });
4

5 に答える 5

14

.classセレクターを使用する必要があります。

// select every <select> element with classname "yourclassname"
$('select.yourclassname').each(function() {
    // $(this) now refers to one specific <select> element
    // we append an option to it, like you asked for
    $(this).append(
        $('<option value="foo">Bar</option>');
    );
});

jQueryを使用して要素を適切に選択する方法の詳細については、http://docs.jquery.com/Selectorsを参照してください

于 2010-01-14T14:14:42.917 に答える
7

これを試してみてください:

$('select.className').each(function() {
   var currentSelect = $(this);
   // ... do your thing ;-)
});
于 2010-01-14T14:16:19.433 に答える
7

新しい質問に答えるには、次の行を使用して、 :<option>を含むすべてのを削除できます。currentComponentName

$('select.componentSelect option:contains("' + currentComponentName + '")').remove();

デモ

于 2010-01-14T14:50:43.673 に答える
1

currentComponentName私があなたの選択のオプションの1つであると定義する限り、あなたの投稿されたjQueryコードは私のために働きます。Aron Rotteveelの答えは非常に近いですが、追加部分が少しずれています。これを試してください。

$('select.componentSelect').each(function() { 
    $(this).append('<option value="foo">Bar</option>'); 
}); 
于 2010-01-14T15:34:34.987 に答える
1

.className次のように、セレクターを使用する必要があります。

$('select.className')

このセレクターは、要素セレクター(すべての<select>要素に一致)とclassNameセレクター(classNameクラスを含むすべての要素に一致)を組み合わせて、そのクラスのすべての要素を検索します<select>

于 2010-01-14T14:15:47.063 に答える