JavaScript实现日期与星座级联下拉框

作者:纸飞机

时间:2026-10-27

浏览:138

本文提供了一段JavaScript代码,用于实现出生日期与星座的级联显示功能。通过监听年份、月份和日期的变化,动态更新日期选项并计算对应的星座信息。代码包含获取月份天数、判断闰年以及根据日期确定星座的逻辑,适用于Web开发中的用户生日输入场景。

文章目录

JavaScript 实现代码

JavaScript 级联逻辑实现

具体实现如下:

function birthdayOnchange(obj) {
var year = $("<%= DDL_Year.ClientID%>").value;
if (year == "year")
 return;
 else
 year = parseInt(year, 10);
var month = $("<%=DDL_Month.ClientID%>").value;
 if (month == "month")
 return;
 else
 month = parseInt(month, 10);
var day = $("<%=DDL_Day.ClientID%>").value;
 var wholeday = getDays(year, month);
if (1) {
 var options = $("<%=DDL_Day.ClientID%>").options;
 for (var i = 1; i <= wholeday; i++) {
 var j = i.toString();
 j = j.length == 1 ? "0" + j : j;
 options.length = i + 1;
 options[i].value = j;
 options[i].text = j;
 if (day <= wholeday && i == day) {
 options[i].selected = true;
 }
 }
 }
function getDays(year, month) {
 var dayarr = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
if (month == 2) {
 if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 || year < 1900)
 return 29;
 else
 return dayarr[month - 1];
 }
 else {
 return dayarr[month - 1];
 }
 }
function adjustAstro() {
 var v_astro = getAstro($("<%=DDL_Month.ClientID%>").value, $("<%=DDL_Day.ClientID%>").value);
 $("<%=astro.ClientID %>").options[0].text = v_astro;
 }
function getAstro(v_month, v_day) {
 v_month = parseInt(v_month, 10)
 v_day = parseInt(v_day, 10);

html

HTML 下拉列表结构

HTML 结构代码如下:

<DIV>出生日期:</DIV>
<DIV>
<asp:DropDownList ID="DDL_Year" runat="server" onchange="birthdayOnchange(this);"></asp:DropDownList> 年
<asp:DropDownList ID="DDL_Month" runat="server" onchange="birthdayOnchange(this);adjustAstro();"></asp:DropDownList> 月
<asp:DropDownList ID="DDL_Day" runat="server" onchange="adjustAstro();"></asp:DropDownList> 日
</DIV>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章