什么是正确的jquery选择器来获取具有特定类名的所有选择下拉列表?

leo*_*ora 9 jquery select selector drop-down-menu

我想循环所有下拉选择与某个类名称并添加一个项目,我只是在努力与正确的选择器


编辑: 我必须做错事,因为大多数受欢迎的答案似乎没有工作,所以我认为我的代码必须有一些怪癖.我已粘贴下面的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>
Run Code Online (Sandbox Code Playgroud)

等等...

jquery代码:

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

    });
Run Code Online (Sandbox Code Playgroud)

Aro*_*eel 12

您应该使用.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>');
    );
});
Run Code Online (Sandbox Code Playgroud)

有关如何使用jQuery正确选择元素的更多信息,请查看http://docs.jquery.com/Selectors.


SLa*_*aks 7

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

$('select.componentSelect option:contains("' + currentComponentName + '")').remove();
Run Code Online (Sandbox Code Playgroud)

演示


Mic*_*all 5

试一试:

$('select.className').each(function() {
   var currentSelect = $(this);
   // ... do your thing ;-)
});
Run Code Online (Sandbox Code Playgroud)