jQuery删除除current之外的选项 [英] jQuery remove options except current

查看:98
本文介绍了jQuery删除除current之外的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个选择框,每个框包含完全相同的数据:

I have 4 select boxes, each containing the exact same data:


  • 骑马

  • 钓鱼

  • 吸烟

  • 飞行

  • Riding
  • Fishing
  • Smoking
  • Flying

如果我在选择框[0]并选择骑马时,我想从剩下的每个选项框中删除该选项,除了我当前有效的选择框。

If I'm in select-box[0] and select "Riding", I want to remove the option from each of the remaining except the current select-box I have active.

我已经尝试过选择:not(:first-child)但是这将删除,只有第一个孩子是选择,而不是任何其他孩子。

I've tried select:not(:first-child) but this will remove, only if the first child is the selection, not any of the other.

基本上,我需要从所有下拉菜单中删除一个选定的选项,除了我选择的那个。

Basically, I need to remove a selected option from all drop-downs except the one I made the selection on.

推荐答案

试试这个:

$('#select1').on('change', function() {
    var val = this.value;
    $('select').not(this).children().filter(function() {
        return this.value === val;
    }).remove();
});

即。对于每个< select> 而不是,获取孩子,但是过滤器那些 .value 与我的不同,删除他们。

i.e. for every <select> that is not this, get its children, but filter the ones whose .value is not the same as mine, and remove them.

http://jsfiddle.net/alnitak/CJYWn/

如果您需要在第一个条目更改为某些内容时重新添加元素否则,您可能会考虑克隆整个第一个选择,同时过滤掉不需要的项目。

If you need to re-add elements when the first entry is changed to something else, you might consider just cloning the entire first select whilst filtering out the unwanted items.

在这种情况下过滤器需要!== ,因为我们希望之外的所有元素匹配,即

In this case the filter would need !==, since we want all of the elements except the one that matches, i.e.

$('#select1').on('change', function() {
    var val = this.value;
    $('select').not(this).empty().append($(this).children().filter(function() {
        return this.value !== val;
    }).clone());
});

工作演示 http://jsfiddle.net/alnitak/ARUmX/

这篇关于jQuery删除除current之外的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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