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

要回答您的新问题,您可以使用以下行删除所有<option>包含 a 的 s currentComponentName

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

演示

于 2010-01-14T14:50:43.673 回答
7

试一试:

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

您需要使用.className选择器,如下所示:

$('select.className')

此选择器将元素选择器(匹配所有<select>元素)与 className 选择器(匹配包含className该类的所有元素)结合起来,以查找<select>具有该类的所有元素。

于 2010-01-14T14:15:47.063 回答
1

只要我定义currentComponentName为您选择的选项之一,您发布的 jQuery 代码就对我有用。Aron Rotteveel 的回答非常接近,但附加部分有点偏离,试试这个:

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