根据每个Div的生日计算年龄

时间:2016-02-12 03:25:06

标签: jquery

我有一个JQuery代码来根据日期计算年龄,但我似乎无法应用于多个Div

<div class="bday">
     <span id="age"></span>
     <span id="birthdate">01/21/1983</span>
</div>
<div class="bday">
     <span id="age"></span>
     <span id="birthdate">01/21/1982</span>
</div>
<div class="bday">
     <span id="age"></span>
     <span id="birthdate">01/21/1981</span>
</div>

$('#birthdate').each(function() {
    var ptag = $(this).text();
    var birthdate = new Date(ptag);
    var cur = new Date();
    var diff = cur - birthdate;
    var age = Math.floor(diff / 31536000000);
    $('#age').append(age);
});

我累了课,但所有年龄都出现在每个范围内。 我还能做些什么来让这个代码适用于每个div而不是它出现在一个div上?

2 个答案:

答案 0 :(得分:0)

请使用此HTML:

<div class="bday">
     <span class="age"></span>
     <span class="birthdate">01/21/1983</span>
</div>
<div class="bday">
     <span class="age"></span>
     <span class="birthdate">01/21/1982</span>
</div>
<div class="bday">
     <span class="age"></span>
     <span class="birthdate">01/21/1981</span>
</div>

请使用此脚本:

$('.birthdate').each(function() {
    var ptag = $(this).text();
    var birthdate = new Date(ptag);
    var cur = new Date();
    var diff = cur - birthdate;
    var age = Math.floor(diff / 31536000000);
    $(this).closest('.bday').find(".age").text(age);
});

我只将id更改为Class并追加行。

答案 1 :(得分:0)

当我评论你的问题时,你必须将所有的东西改为类,然后使用最近的函数冷却找到父母,然后找到另一个孩子,这是生日的兄弟。

而且你也不能使用追加,因为它会随时追加以前的数据。所以使用text()或html()。

您修改过的jQuery:

$('.birthdate').each(function() {
    var ptag = $(this).text();
    var birthdate = new Date(ptag);
    var cur = new Date();
    var diff = cur - birthdate;
    var age = Math.floor(diff / 31536000000);
    $(this).closest("div").find('.age').html(age);
});

您修改的HTML:

<div class="bday">
     <span class="age"></span>
     <span class="birthdate">01/21/1983</span>
</div>
<div class="bday">
     <span class="age"></span>
     <span class="birthdate">01/21/1982</span>
</div>
<div class="bday">
     <span class="age"></span>
     <span class="birthdate">01/21/1981</span>
</div>