本文示範如何根據使用者輸入的月與日,即時判斷對應的星座,並對超出範圍的日期給出提示。
function xingzuo() {
var date=document.getElementById("txtDay").value, month=document.getElementById("txtMonth").value;
with (document.getElementById("txtXZ")){
if (month == 1 && date >=20 || month == 2 && date <=18) {value = "水瓶座";}
if (month == 1 && date > 31) {value = "日期有誤";}
if (month == 2 && date >=19 || month == 3 && date <=20) {value = "雙魚座";}
if (month == 2 && date > 29) {value = "日期有誤";}
if (month == 3 && date >=21 || month == 4 && date <=19) {value = "白羊座";}
if (month == 3 && date > 31) {value = "日期有誤";}
if (month == 4 && date >=20 || month == 5 && date <=20) {value = "金牛座";}
if (month == 4 && date > 30) {value = "日期有誤";}
if (month == 5 && date >=21 || month == 6 && date <=21) {value = "雙子座";}
if (month == 5 && date > 31) {value = "日期有誤";}
if (month == 6 && date >=22 || month == 7 && date <=22) {value = "巨蟹座";}
if (month == 6 && date > 30) {value = "日期有誤";}
if (month == 7 && date >=23 || month == 8 && date <=22) {value = "獅子座";}
if (month == 7 && date > 31) {value = "日期有誤";}
if (month == 8 && date >=23 || month == 9 && date <=22) {value = "處女座";}
if (month == 8 && date > 31) {value = "日期有誤";}
if (month == 9 && date >=23 || month == 10 && date <=22) {value = "天秤座";}
if (month == 9 && date > 30) {value = "日期有誤";}
if (month == 10 && date >=23 || month == 11 && date <=21) {value = "天蠍座";}
if (month == 10 && date > 31) {value = "日期有誤";}
if (month == 11 && date >=22 || month == 12 && date <=21) {value = "射手座";}
if (month == 11 && date > 30) {value = "日期有誤";}
if (month == 12 && date >=22 || month == 1 && date <=19) {value = "摩羯座";}
if (month == 12 && date > 31) {value = "日期有誤";}
}
}
原理是針對每個星座列出「起訖月日」的兩段條件,命中即賦值;同時對每月超出天數的情況回傳提示,避免使用者輸入像 2 月 30 日這種不存在的日期。