我有 4 个选择框,每个都包含完全相同的数据:
- 骑马
- 钓鱼
- 吸烟
- 飞行
如果我在选择框 [0] 中并选择“骑行”,我想从剩余的每个选项中删除该选项,除了当前处于事件状态的选择框之外。
我尝试过 select:not(:first-child) 但这只会删除,只有第一个 child 是选择,而不是其他 child 。
基本上,我需要从所有下拉列表中删除选定的选项,除了我选择的选项之外。
最佳答案
试试这个:
$('#select1').on('change', function() {
var val = this.value;
$('select').not(this).children().filter(function() {
return this.value === val;
}).remove();
});
即对于每个 <select>
即not this
,得到其children
,但是filter
那些 .value
和我的不一样,并且remove
他们。
工作演示位于 http://jsfiddle.net/alnitak/CJYWn/
如果您需要在第一个条目更改为其他内容时重新添加元素,您可以考虑克隆整个第一个 select
同时过滤掉不需要的项目。
在这种情况下,过滤器需要 !==
,因为我们想要除匹配的元素之外的所有元素,即
$('#select1').on('change', function() {
var val = this.value;
$('select').not(this).empty().append($(this).children().filter(function() {
return this.value !== val;
}).clone());
});
关于jQuery 删除除当前选项之外的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9112112/