gpt4 book ai didi

javascript - jQuery on change 仅显示所选选项,删除/禁用其余选项

转载 作者:行者123 更新时间:2023-11-28 04:53:12 25 4
gpt4 key购买 nike

目标:从选择下拉菜单中,如果有人选择了一个选项,则禁用/删除/隐藏该下拉菜单中的其余选项。

这是下拉菜单。如果有人选择“1”,其余选项 (2,3,4) 将被删除/禁用/隐藏:

<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:

$('.selectDropdown').on('change', function(e) {
$(this).closest('.abc').children('.xyz').children('option:not(:selected)').prop('disabled', true);
});

我知道,这里的 JavaScript 有问题。我哪里做错了?

最佳答案

保持简单并使用:

$('.selectDropdown').on('change', function(e) {
$(this).children('option:not(:selected)').prop('disabled', true);
});

在此上下文中,$(this) 指的是 .selectDropdown 并且 option 元素是子元素。

Example Here


..如果你想删除未选择的 child :

$('.selectDropdown').on('change', function(e) {
$(this).children('option:not(:selected)').remove();
});

Example Here


您的代码无法正常工作的原因是 option 元素不是.xyz 元素的直接子元素。你将不得不使用:

$('.selectDropdown').on('change', function(e) {
$(this).closest('.abc').children('.xyz').children().children('option:not(:selected)').prop('disabled', true);
});

(我只是在 .children('.xyz') 之后链接了另一个 .children() 方法..)

关于javascript - jQuery on change 仅显示所选选项,删除/禁用其余选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28161765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com