gpt4 book ai didi

javascript - 我已经尝试在下拉列表中列出过去 20 年。但无法将其显示为 Year to Year 形式的范围

转载 作者:行者123 更新时间:2023-11-30 12:14:23 29 4
gpt4 key购买 nike

我从今年过去了 20 年。但目前我希望它显示为年复一年。例如:1992 - 1999 1999 - 2002 2003 - 2015

这是我的代码。

function populatedropdown(yearfield) {
var today = new Date(),
yearfield = document.getElementById(yearfield),
beforeYears = 20
thisyear = today.getFullYear();

for (var year = thisyear-beforeYears, index = 0;
index <= beforeYears;
index++, year++) {
yearfield.options[index] = new Option(year, year);
}
yearfield.value = thisyear;
//select today's year
}

//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload = function() {
populatedropdown("yeardropdown")
}
<td><select id="yeardropdown"/></td>

这是我希望拥有的理想输出 year to year

最佳答案

我不确定我是否正确理解了你的问题,但如果我理解了,它比你已经拥有的更容易:

function populatedropdown(yearfield) {
var today = new Date(),
yearfield = document.getElementById(yearfield),
beforeYears = 20,
thisYear = today.getFullYear(),
firstYear = thisYear - beforeYears,
yearRange = firstYear + ' - ' + thisYear;

yearfield.options[0] = new Option(yearRange, yearRange);
yearfield.value = yearRange;
}

//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload = function() {
populatedropdown("yeardropdown")
}
<select id="yeardropdown"/>


更新

由于您已经更新了您的问题,这里是我提出的解决方案:

(function(d) {
d.addEventListener('DOMContentLoaded', function() {
var currentYear = new Date().getFullYear(),
totalYears = 20,
firstYear = currentYear - totalYears;

var fromYear = d.getElementById('fromYear'),
toYear = d.getElementById('toYear');

for (var i = firstYear; i <= currentYear; i++) {
var opt = d.createElement('option');
opt.value = i;
opt.textContent = i;

fromYear.appendChild(opt);
toYear.appendChild(opt.cloneNode(true));
}

toYear.value = currentYear;

/* if you don't want to disable the impossible selections, remove the code below */
disableYears();

fromYear.addEventListener('change', disableYears);
toYear.addEventListener('change', disableYears);

function disableYears(e) {
[].forEach.call(fromYear.querySelectorAll('option'), function(opt, i) {
opt.disabled = opt.value > toYear.value;
});

[].forEach.call(toYear.querySelectorAll('option'), function(opt, i) {
opt.disabled = opt.value < fromYear.value;
});
}
/* if you don't want to disable the impossible selections, remove the code above */
});
})(document);
<select id='fromYear'></select>
<select id='toYear'></select>

关于javascript - 我已经尝试在下拉列表中列出过去 20 年。但无法将其显示为 Year to Year 形式的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32834836/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com