我有两个选项清单
第一列表
0xmomedaaaaaaaaaaaaaaaaaaaa测试
第二列表
我想检查第二个列表中是否存在值,如果是,从第一个列表中删除它。
我试过用这个函数
var e = document.getElementById('0');
var f = document.getElementById('5');
var output = [];
for(var a= e.options.length-1; a >= 0; a--) {
output.push(e.options[a].value);
}
console.log(output);
for(var b= f.options.length-1; b >= 0; b--) {
if (output.includes(f.options[b].value)){
var i=output.indexOf(f.options[b].value);
console.log(i);
e.remove(i);
}}但是,它处理列表中的一个项,而不是两个或多个,它从第一个列表中删除不同的选项,我认为这是因为当第二个循环之后删除一个项时,第一个列表中的项将有不同的indexes...maybe不确定
希望有人能帮忙
发布于 2020-05-19 06:20:36
使用过滤器函数的Jquery解决方案:
$('#0 option').filter(function(){
return $('#5 option[value='+this.value+']').length > 0
}).remove();
$('#0 option').filter(function(){
return $('#5 option[value='+this.value+']').length > 0
}).remove();<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="0" multiple="" size="6">
<option value="0xmohamed">0xmohamed</option>
<option value="aaaaaaaaaaa">aaaaaaaaaaa</option>
<option value="test">test</option></select>
<select id="5" name="ary[]" multiple="" size="6">
<option value="aaaaaaaaaaa">aaaaaaaaaaa</option>
<option value="test">test</option> </select>
发布于 2020-05-19 06:19:06
我把第一个循环改为
for(var a=0; a <= e.options.length-1; a++)因此,阵列被填充提升方式,而且它工作了。
发布于 2020-05-19 06:27:26
请检查removeOptionIfExits函数。我在代码中添加了注释行中的解释。
// Remove options from first select which already exist in second select.
function removeOptionIfExits() {
// retrieve values from the second select
var values = $("#5 option").toArray().map(x => x.value);
// find all options from first select.
// filter those options which has value exist in second select
// loop through it and remove.
$("#0 option").toArray()
.filter(x => values.includes(x.value))
.forEach(x => x.remove());
}
// Call remove function after document ready.
$(document).ready(function(){
removeOptionIfExits();
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<select id="0" multiple="" size="6">
<option value="0xmohamed">0xmohamed</option>
<option value="aaaaaaaaaaa">aaaaaaaaaaa</option>
<option value="test">test</option>
</select>
<select id="5" name="ary[]" multiple="" size="6">
<option value="aaaaaaaaaaa">aaaaaaaaaaa</option>
<option value="test">test</option>
</select>
https://stackoverflow.com/questions/61884397
复制相似问题