我是JS新手,我的脚本有问题。 我希望在我的网站上显示员工的资历日期。 这是我的JS代码来计算它。
var dateObj1 = new Date( '1992/07/07 18:00:00' );
var dateObj2 = new Date();
//get difference in milliseconds
var diffMilliseconds = dateObj1.getTime() - dateObj2.getTime();
//make the difference positive
if( diffMilliseconds < 0 ) diffMilliseconds *= -1;
//convert milliseconds to hours
var diffYears = ( diffMilliseconds / 1000 ) / 60 / 60 / 24 / 365;
//print on console
var num = diffYears;
num = Math.floor(num);
if (num > 1)
{
document.write(num + ' years');
}
else if (num < 1)
{
document.write('less than one year');
}
else
{
document.write(num + ' year');
}
将有大约45-50名员工,而不是创建50个js文件想要在HTML中定义就业日期var dateObj1 = new Date( '1992/07/07 18:00:00' );
,但不知道如何做到这一点。
有人可能会发布部分HTML代码以及必须更改的JS部分。
谢谢。答案 0 :(得分:0)
您可以创建一个包含员工姓名及其指定日期的地图(对象)。然后你采用你所拥有的逻辑来计算剩余的时间(然后显示它),然后把它放在一个循环中。对于地图中的每位员工,计算数字然后打印。
答案 1 :(得分:0)
通过将代码放在函数中,并通过它传递HTML中的数据,它应该会产生一些好的结果。
<强> HTML 强>
<table>
<thead>
<tr>
<td>Name</td>
<td>Startdate</td>
<td>Date in years</td>
</tr>
</thead>
<tbody>
<tr>
<td>Employee #1</td>
<td>1992/07/07 18:00:00</td>
</tr>
<!-- More employees -->
</tbody>
</table>
<强>的JavaScript 强>
var rows = document.querySelectorAll("tbody tr"); // Get all the rows
for(var i = 0; i < rows.length; i++) {
// For each row, get the start date
var startdate = rows[i].cells[1].innerText,
years = calculateYears(startdate);
// Create a DOM element with the result, and add it to the table
var td = document.createElement("td"),
result = document.createTextNode(years);
td.appendChild(result);
rows[i].appendChild(td);
}
// Years calculation
function calculateYears(startdate) {
// Your function, slightly modified
}
<强> Here's the result! 强>