嗨,我想知道如何基于来自两个日期选择器输入值的日期周期或天数来动态增加表列,并将日期放置为列的标题。我用它来过滤数据库中的数据以建立出勤示例。 以下是创建表标题单元格但使用按钮的代码
<!DOCTYPE html>
<html>
<head>
<style>
table, th {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr id="myTr">
</tr>
</table>
<p>Click the button to create a TH element.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.createElement("TH");
var t = document.createTextNode("table header cell");
x.appendChild(t);
document.getElementById("myTr").appendChild(x);
}
</script>
</body>
</html>
和以下代码如何获取2个日期选择器值,但不知道如何计算这些值之间的时间间隔以及如何将其作为列增加的逻辑注入
<!DOCTYPE html>
<html>
<body>
<h3>A demonstration of how to access a Date field</h3>
<input type="date" id="startdate" value="2014-02-09">
<br>
<input type="date" id="enddate" value="2014-02-09">
<p>Click the button to get the date of the date field.</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> input elements with type="date" do not show as any date field/calendar in IE 11 and earlier versions.</p>
<p id="demo"></p>
<br>
<p id="demo1"></p>
<script>
function myFunction() {
var x = document.getElementById("startdate").value;
document.getElementById("demo").innerHTML = x;
var x = document.getElementById("enddate").value;
document.getElementById("demo1").innerHTML = x;
}
</script>
</body>
</html>
感谢您的进阶
答案 0 :(得分:0)
使用moment.js可以轻松处理日期,getDates是用于返回输入之间具有日期的数组的函数。
function myFunction() {
var startDate = document.getElementById("startdate").value;
var endDate = document.getElementById("enddate").value;
var dates = getDates(startDate, endDate);
var thead = document.querySelector('#myTable thead');
thead.innerHTML = ''
for (const date of dates) {
var x = document.createElement("th");
var t = document.createTextNode(date);
x.appendChild(t);
thead.appendChild(x);
}
}
function getDates(startDate, endDate) {
var dateArray = [];
var currentDate = moment(startDate);
var stopDate = moment(endDate);
while (currentDate <= stopDate) {
dateArray.push(moment(currentDate).format('YYYY-MM-DD'))
currentDate = moment(currentDate).add(1, 'days');
}
return dateArray;
}
table,
th {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<input type="date" id="startdate" value="2019-02-09">
<br>
<input type="date" id="enddate" value="2019-02-09">
<p>Click the button to get the date of the date field.</p>
<button onclick="myFunction()">Try it</button>
<table id="myTable">
<thead>
</thead>
</table>