我有一张桌子,里面有一个包含人和他们年龄的tbody和x行数。
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00">13</td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00">14</td>
</tr>
我想显示所有人的正确年龄,但由于这取决于当前日期,我正在考虑进入生日。但我还是想显示玩家的实际年龄。如何使用迭代表的所有行的jQuery脚本,并根据data-date值显示相应td单元格中的实际年龄?
答案 0 :(得分:0)
也许是这样的:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$('.age').each(function(index){
$(this).html(getAge($(this).data('date')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00">13</td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00">14</td>
</tr>
</tbody>
</table>
getAge()函数从这里被盗:https://stackoverflow.com/a/7091965/2008111所以也许您可以关注该链接并在那里提供答案。
答案 1 :(得分:0)
$('.age').each(function(i, e) {
var now = new Date();
var date = new Date(e.dataset.date);
$(this).html(now.getFullYear() - date.getFullYear());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00"></td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00"></td>
</tr>
</tbody>
</table>
答案 2 :(得分:0)
您的HTML页面应如下所示:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="persons">
<tbody>
<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00"></td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00"></td>
</tr>
</tbody>
</table>
js方应如下所示:
$(document).ready(function(){
$('.persons td.age').each(fucntion(){
var today = new Date();
var birthday = new Date($(this).attr('data-date'));
var ageDifMs = today - birthday.getTime();
var ageDate = new Date(ageDifMs);
$(this).html(Math.abs(ageDate.getUTCFullYear() - 1970));
});
});