【发布时间】:2020-07-03 22:13:30
【问题描述】:
我是新手反应。我对 onchange 功能有疑问。我有两个日期字段,“开始”和“结束”日期。我想在“开始日期”中显示“当前月份 + 年份”,如“2020 年 3 月”,在“结束日期”中,我想根据“开始日期”显示“月份和年份”。例如:如果用户在“开始日期”中选择“2020 年 4 月”,我想在“结束日期”中显示“2020 年 4 月至 2021 年 4 月”。根据“开始日期”,我想显示“结束日期”。如果用户在开始日期选择“2020 年 5 月”并且我想显示“2020 年 5 月”,则不应显示 5 月的上个月。我知道我们想通过使用 onchange 来处理这个问题。我在 Jquery 中也取得了同样的成就。在这里,我正在努力完成这项工作。下面是我在下拉列表中获得当前月份和年份的代码。任何人都可以帮助我处理这个案子。提前致谢。
const fareMon = () => {
const monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const currDate = new Date();
const year = currDate.getFullYear();
const months = [];
let currentMonthIndex = currDate.getMonth();
let yearsToAdd = 0;
for (let i = 0; i < 13; i += 1) {
if (currentMonthIndex === 12) {
currentMonthIndex = 0;
yearsToAdd += 1;
}
const futYear = year + yearsToAdd;
months.push(<option value={`${monthList[currentMonthIndex]} ${futYear}`}>{`${monthList[currentMonthIndex]} ${futYear}`}</option>);
currentMonthIndex += 1;
}
return <>{months}</>;
};
Calling function in Drop Down:
<Form.Group className={styles.formGroup}>
<Form.Control required as="select" name="startDate">
<option value="">Months</option>
{fareMon()}
</Form.Control>
</Form.Group>
Below is Jquery code:
function BindFareMonth(targId, currentMonth, selectedYear) {
var startDate = new Date(selectedYear, (currentMonth - 1), 1);
var endDate = new Date(selectedYear, (currentMonth + 11), 1);
$("#" + targId).html("");
$("#" + targId).append('<option value="0">Select Month</option>');
while (startDate <= endDate) {
var ddMopnth = startDate.getMonth() + 1;
ddMopnth = ddMopnth < 10 ? "0" + ddMopnth : ddMopnth;
$("#" + targId).append('<option value="' + startDate.getFullYear() + "-" + ddMopnth + "-01" + '">' + monthNames1[$("body").attr("data-culture")][startDate.getMonth()] + " " + startDate.getFullYear() + '</option>');
startDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 1);
}
};
【问题讨论】:
-
为什么不对你的 React 代码使用相同的 while 方法呢?因为这两个代码有很大的不同
标签: javascript reactjs