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

标签 jquery select drop-down-menu selector

我想循环遍历具有特定类名的所有下拉选择并向其中添加一个项目,而我只是在努力寻找正确的选择器

<小时/>

编辑:我一定做错了什么,因为大多数被投票接受的答案似乎不起作用,所以我认为我的代码中一定有一些怪癖。我已经在下面粘贴了 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();
            }
        });

    });

最佳答案

您应该使用.class selector .

// 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 .

关于jquery - 获取具有特定类名的所有选择下拉列表的正确 jquery 选择器是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2064626/

相关文章:

javascript - 无法在 TouchSwipe jQuery 插件中选择文本

Jquery 单击功能仅适用于 Button 的一个实例

mysql - 从一个表中选择,从另一个 id 链接的表中计数

mysql - 检查新用户名是否不在两个单独的表中

PHP foreach 循环,getElementById 的唯一 <select> id

javascript - 为什么JS不在滚动时调用函数?

javascript - jQuery 取消先前排队的事件处理程序以重新启动 CSS 动画

php - ZF2 select 不显示任何结果

javascript - 在reactjs中切换下拉菜单

javascript - 未捕获的类型错误 : Object function () has no method 'replace'