我想循环遍历具有特定类名的所有下拉选择并向其中添加一个项目,而我只是在努力寻找正确的选择器
<小时/>编辑:我一定做错了什么,因为大多数被投票接受的答案似乎不起作用,所以我认为我的代码中一定有一些怪癖。我已经在下面粘贴了 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/