更改时jQuery仅显示选定的选项,删除/禁用其余选项 [英] jQuery on change only shows the selected option, remove/disable rest of them

查看:69
本文介绍了更改时jQuery仅显示选定的选项,删除/禁用其余选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆