更改时jQuery仅显示选定的选项,删除/禁用其余选项 [英] jQuery on change only shows the selected option, remove/disable rest of them
问题描述
目标:如果有人选择了某个选项,则从选择下拉菜单中禁用/删除/隐藏该下拉菜单中的其余选项.
Target: From a select dropdown menu, if someone selects an option, disable/remove/hide the rest of the options on that dropdown menu.
这是下拉菜单.如果有人选择"1",则其余选项(2、3、4)将被删除/禁用/隐藏:
Here is the dropdown menu. If someone selects "1", the rest of options (2,3,4) will be removed/disabled/hide:
<div class="abc">
<div class="xyz">
<select name="pqr" class="selectDropdown">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
</div>
</div>
这是我尝试使用的JavaScript:
Here is the JavaScript I tried to use:
$('.selectDropdown').on('change', function(e) {
$(this).closest('.abc').children('.xyz').children('option:not(:selected)').prop('disabled', true);
});
我知道,这里的JavaScript错误.我在哪里弄错了?
I know, the JavaScript is faulty here. Where did I make the mistake?
推荐答案
保持简单并使用:
$('.selectDropdown').on('change', function(e) {
$(this).children('option:not(:selected)').prop('disabled', true);
});
在这种情况下,$(this)
指的是.selectDropdown
,而option
元素是子元素.
In this context, $(this)
refers to .selectDropdown
and the option
elements are the children.
..以及如果要删除未选择的子代:
..and if you want to remove the unselected children:
$('.selectDropdown').on('change', function(e) {
$(this).children('option:not(:selected)').remove();
});
您的代码无法正常运行的原因是,option
元素不是
The reason your code wasn't working was because the option
elements are not direct children of the .xyz
element. You would have had to use:
$('.selectDropdown').on('change', function(e) {
$(this).closest('.abc').children('.xyz').children().children('option:not(:selected)').prop('disabled', true);
});
(我只是在.children('.xyz')
之后链接了另一个.children()
方法.)
(I simply chained another .children()
method after .children('.xyz')
..)
这篇关于更改时jQuery仅显示选定的选项,删除/禁用其余选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!