简体   繁体   English

使用JQuery根据生日计算年龄

[英]Calculate age based on birthday with JQuery

I am trying to calculate how old a person is with jQuery. 我正在尝试计算jQuery的年龄。 I tried using this code but I am not getting any results. 我尝试使用此代码,但未得到任何结果。 I assume that I cannot but a varible in date(). 我假设我只能在date()中使用变量。 What could I do to make this work? 我该怎么做才能使这项工作?

<p id="age">2015/01/01</p>


var ptag = $('#age');
var birthdate = new Date(ptag);
var cur = new Date();
var diff = cur-birthdate;
var age = Math.floor(diff/31536000000);
alert(age);

您需要获取#age元素的内容 ,而不是元素本身。

var ptag = $('#age').text();

var age = new Date() - new Date($('#age').text());
age /= 31536000000;

$(selector).text() will return the content of a DOM element as a text. $(selector).text()将以文本形式返回DOM元素的内容。 And since we do not want to use a bunch of variables, we simply define one, as the difference of two dates: the 'now' minus the one from the text. 而且由于我们不想使用一堆变量,因此我们仅将一个变量定义为两个日期的差:“现在”减去文本中的一个。 And since the above is in miliseconds, we devied it... and that will return age in years. 由于上面的信息以毫秒为单位,因此我们将其偏离了……这将以年为单位返回年龄。

jQuery .text() jQuery .text()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM