项目中用到的一些简单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>
效果图: