var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var array = [];
let sel1 = false;
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
if(array.length === 1 && !sel1) array.unshift(one);
else array.splice(0,1,one);
console.log(array);
sel1 = true;
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
array.splice(sel1, 1, two);
console.log(array);
}
function myFunct3() {
var three = select3.options[select3.selectedIndex].value;
}
<select id = 'select1' onchange = 'myFunct1()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog1'>Dog</option>
<option value = 'Cat1'>Cat</option>
<option value = 'Bear1'>Bear</option>
</select>
<select id = 'select2' onchange = 'myFunct2()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog2'>Dog</option>
<option value = 'Cat2'>Cat</option>
<option value = 'Bear2'>Bear</option>
</select>
<select id = 'select3' onchange = 'myFunct3()'>
<option disabled selected value> -- select an option -- </option>
<option value = 'Dog3'>Dog</option>
<option value = 'Cat3'>Cat</option>
<option value = 'Bear3'>Bear</option>
</select>
我有这种方法,可以通过两个选择菜单完全按照我的需要工作。因此,如果您从第二个中连续选择两次,则选择数组的长度永远不会超过一个,直到您从第一个中选择。现在,我要合并第三个选择菜单。请帮助我完成这项工作。我知道我可以将它们全部组合成一个函数,而不必处理这些问题,但是对于我来说,我做不到。主要条件是,阵列中不会有来自同一选择菜单的多个选择,阵列中也永远不会有任何空位置计入其长度。因此不会出现[undefined,Cat2]数组。
答案 0 :(得分:1)
简单的方法是:
<div class="col-md-4 bg-warning">状態</div>
<div class="col-md-8 pd-all-2px">
<select class="form-control" id="approvalstate" th:field="*{approvalstate}">
<option th:value="0" th:text="未返信"></option>
<option th:value="1" th:text="返信済"></option>
</select>
</div>
(将字符串保留在原始索引处)。例如,realArr
的值将始终设置为select1
,而realArr[0]
的值将始终设置为select2
... realArr[1]
是您将使用showArr
删除undefined
的数组
filter()
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
var select3= document.getElementById('select3');
var realArr = [];
var showArr = [];
function myFunct1() {
var one = select1.options[select1.selectedIndex].value;
realArr[0] = one;
showArr = realArr.filter(x => x !== undefined);
console.log(showArr);
}
function myFunct2() {
var two = select2.options[select2.selectedIndex].value;
realArr[1] = two
showArr = realArr.filter(x => x !== undefined);
console.log(showArr);
}
function myFunct3() {
var three = select3.options[select3.selectedIndex].value;
realArr[2] = three;
showArr = realArr.filter(x => x !== undefined);
console.log(showArr);
}