其他分享
首页 > 其他分享> > JS下拉框年月

JS下拉框年月

作者:互联网

项目中用到的一些简单JS小知识,动态创建年月下拉框:

 

 

JS代码:

var date = new Date();

var y = date.getFullYear();

var m = date.getMonth() + 1;

 

for (i = 0; i < 10; i++) {

var oP = document.createElement("option");

var oText = document.createTextNode(y);

oP.appendChild(oText);

oP.setAttribute("value", y);

document.getElementById('year').appendChild(oP);

y = y - 1;

};

 

var j = 1;

 

for (i = 1; i < 13; i++) {

var month = document.createElement("option");

var monthText = document.createTextNode(j);

month.appendChild(monthText);

month.setAttribute("value", j);

if (j == m) {

month.setAttribute("selected", "selected");

}

;

document.getElementById('month').appendChild(month);

j = j + 1;

};

 

 

HTML页面:

年份:

<select id="year">   </select>

月份:

<select id="month">  </select>

 

效果图:

 

标签:appendChild,JS,month,var,document,下拉框,oP
来源: https://www.cnblogs.com/123525-m/p/15668600.html