答案 0 :(得分:2)
尝试以下代码段-代码说明一切:
// re-write the options
const updateOptionElements = (elt, low, high, selected = null) => {
elt.innerHTML = '';
for (let i=low; i<high; i++) {
let option = document.createElement('option');
option.innerHTML = ''+i;
if (i==selected) option.setAttribute('selected', 'true');
elt.appendChild(option);
}
}
// initialize DOM selectors and variables value bindings
const to = document.querySelector('#to');
const from = document.querySelector('#from');
let toSelected = 0;
let fromSelected = 9;
// initializes options
updateOptionElements(to, 0, 10, toSelected);
updateOptionElements(from, 0, 10, fromSelected);
// add change listeners to update the options upon change
to.onchange = evt => {
toSelected = +evt.target.value;
updateOptionElements(from, toSelected+1, 10, fromSelected);
}
from.onchange = evt => {
fromSelected = +evt.target.value;
updateOptionElements(to, 0, fromSelected, toSelected);
}
<select id="to"></select>
<select id="from"></select>
答案 1 :(得分:2)
只需将先前选择的值设置为临时变量(value
),然后将其再次设置为innerHTML
之后的选择值
function updateTo(e) {
var to = document.getElementById("to");
var value = to.value;
update(to, e.value, 6);
to.value = value < e.value ? e.value : value;
}
function updateFrom(e) {
var from = document.getElementById("from");
var value = from.value;
update(from, 1, e.value);
from.value = value;
}
function update(elmnt, beginValue, endValue) {
selections = ""
for (var i = beginValue; i <= endValue; i++) {
selections += "<option>" + i.toString() + "</option>";
}
elmnt.innerHTML = selections;
}
<h3>FROM:</h3>
<select id="from" onchange="updateTo(this)">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
<h3>TO:</h3>
<select id="to" onchange="updateFrom(this)">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>