javascript - 根据在类型周的输入中选择的周更改标签天
问题描述
我正在尝试使用 Chart.js 更改标签的日期,但它向我显示了输入类型周中所选周的日期,我拥有的代码如下:
<div class="card-body">
<input class="form-control" type="week" value="2021-W32" id="example-week-input">
<canvas id="myChart1"></canvas>
</div>
下面我留下执行的 javascript 代码。
var ctx1 = document.getElementById('myChart1').getContext('2d');
var chart = new Chart(ctx1, {
type: 'line',
data: {
labels: ['09/08/2021', '10/08/2021', '11/08/2021', '12/08/2021', '13/08/2021', '14/08/2021', '15/08/2021'],
datasets: [{
label: 'Ventas Dirias Sitio Web',
backgroundColor: 'rgb(228, 0, 43)',
borderColor: 'rgb(228, 0, 43)',
data: [0, 0, 0, 0, 0, 0, 0]
}
]},
options: {}
});
我将非常感谢您的帮助。
解决方案
您可以使用以下方式处理一周的渲染:
// function to get first day of the week
function FirstDayOfWeek(w, y) {
let date = new Date(y, 0, (1 + (w) * 7));
date.setDate(date.getDate() + (1 - date.getDay())); // 0 - Sunday, 1 - Monday etc
return date
}
// function to format the date to dd/MM/yyyy
function FormatDate(d)
{
var dd = d.getDate();
var mm = d.getMonth() + 1;
var yyyy = d.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return dd + '/' + mm + '/' + yyyy;
}
function RenderChart() {
let week = document.getElementById("example-week-input").value
let year = week.split("-")[0]*1,
weekNumber = week.split("-")[1].substring(1)*1; // to skip the W
let currentDay = FirstDayOfWeek(weekNumber, year); // get the first day of the week
let chartLabels = [];
for (let i = 0; i < 7; i++)
{
chartLabels.push(FormatDate(currentDay));
currentDay.setDate(currentDay.getDate() + 1); // move to next day
}
// render chart with the new days label
var ctx1 = document.getElementById('myChart1').getContext('2d');
var chart = new Chart(ctx1, {
type: 'line',
data: {
labels: chartLabels,
datasets: [{
label: 'Ventas Dirias Sitio Web',
backgroundColor: 'rgb(228, 0, 43)',
borderColor: 'rgb(228, 0, 43)',
data: [0, 0, 0, 0, 0, 0, 0]
}
]},
options: {}
});
}
然后你只需要修改你的星期选择器,在“onchange”事件中添加对“RenderChart()”的调用。您还可以在页面加载时调用该函数以自动呈现选定的星期。
<input class="form-control" type="week" value="2021-W32" id="example-week-input" onchange="RenderChart()">
推荐阅读
- algorithm - 不可能的搜索算法面试题
- javascript - 无法使用 ionic 4 在 Android 中建立套接字连接
- x509certificate - 设备注册(使用 DPS)和设备到 IOT Hub 通信,无需 SDK
- java - Android 视图中真实世界的维度有多可靠?
- python - 如何检查字符串中的值/字符是否等于整数。Python
- c++ - 带有 if 属性的 For 循环
- powershell - 如何只取出字符串的一部分
- typescript - 推断地图中键的类型(同时在地图中键入值)
- c# - 使用discard关键字丢弃任务会导致任何副作用吗?
- c++ - 调用“make_function”没有匹配的函数