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). 如果您有更多問題,請告訴我。
添加回答
舉報
