1 回答
TA贡献1821条经验 获得超6个赞
您可以通过单击“运行代码片段”来运行下面的代码。如果用户输入 3,选择的选项将变为“3.Madrid”。西班牙语让我很困惑,所以我把它换成了英语,但编程逻辑是一样的。
<form method="GET">
<br>
<select id="provincias">
<option value="0">0.Selecciona...</option>
<option value="1">1.Albacete</option>
<option value="2">2.Murcia</option>
<option value="3">3.Madrid</option>
</select>
<br>
<input type="button" value="Cambiar" onclick="cambiaSelect()">
</form>
<script>
function cambiaSelect() {
var provinces = document.getElementById("provincias");
var position = provinces.selectedIndex;
var select = provinces.options[position].value;
var pantalla;
if (provinces.options[position].value == 0) {
alert("You have not selected any province");
} else {
if (provinces.options[position].selected == true) {
pantalla = prompt("You have selected the province: " + provinces.options[position].text + "\n Choose another province here");
while (true) {
if (pantalla) { // this ensures that if the user clicks cancel on the prompt, we don't do any more logic
if (pantalla === "") {
alert("The value you entered does not exist. Try again!");
} else if (select === pantalla) {
alert("That province is already selected");
} else if (pantalla >= 1 && pantalla <= 3) {
document.getElementById('provincias').selectedIndex = pantalla;
break;
}
pantalla = prompt("Choose another province here");
} else { // if the cancel button on prompt was pressed, get out of loop
break;
}
}
}
}
}
</script>
唯一的问题是如果用户输入了一个介于 1 和 3 之间的不是整数的数字,比如 2.5。2.5 不是一个合适的索引,对吧?因此,如果您想处理这种情况,可以添加以下修改:
else if (Number.isInteger(Number(pantalla)) && pantalla >= 1 && pantalla <= 3). 如果您有更多问题,请告诉我。
添加回答
举报
