基於Asp.net與Javascript控制的日期控制項_javascript技巧

來源:互聯網
上載者:User

控制項效果如下:

從左至右:month,day,year

.cs檔案初始化這三個下拉式清單

複製代碼 代碼如下:

private void BindBirthDay(int day, int month, int year)
{
int dayNow = day;
int monNow = month;
int yearNow = year;
//binding Month
for (int i = 1; i <= 12; i++)
{
ddlBirMon.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlBirMon.Items[monNow - 1].Selected = true;
//binding Day
int daysOfMonth = DateTime.DaysInMonth(yearNow, monNow);
for (int i = 1; i <= daysOfMonth; i++)
{
ddlBirDay.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlBirDay.Items[dayNow - 1].Selected = true;
//binding Year
for (int i = 20; i > 0; i--)
{
ddlBirYear.Items.Add(new ListItem((yearNow - i).ToString(), (yearNow - i).ToString()));
}
for (int i = 0; i < 20; i++)
{
ddlBirYear.Items.Add(new ListItem((yearNow + i).ToString(), (yearNow + i).ToString()));
}
ddlBirYear.Items.FindByValue(yearNow.ToString()).Selected = true;
}

js代碼如下(自己寫的,不保證完全正確啊):
複製代碼 代碼如下:

function ChangeDay() {
var month = document.getElementById("<%=ddlBirMon.ClientID %>");
var year = document.getElementById("<%=ddlBirYear.ClientID %>");
var day = document.getElementById("<%=ddlBirDay.ClientID %>");
if (month.selectedIndex == 3 || month.selectedIndex == 5 || month.selectedIndex == 8 || month.selectedIndex == 10) {
if (day.length == 31) {
if (day.options[30].selected == true) {
day.options[29].selected = true;
}
day.remove(30);
}
}
else{
while (day.length < 31) {
day.add(new Option(day.length+1,day.length+1));
}
}
if (month.selectedIndex == 1) {
if (day.length > 28) {
if (day.selectedIndex == 28) {
day.options[27].selected = true;
}
while (day.length > 28) {
day.remove(day.length - 1);
}
}
var sy = year.options[year.selectedIndex].value;
if ((sy % 4 == 0 && sy % 100 != 0) || (sy % 400==0)) {
day.add(new Option("29", "29"));
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.