0

嘿 javascript 大师们,

尝试为客户的网站创建年龄验证页面。下面的代码不起作用,因为无论您选择哪一年,它仍然允许您进入该站点。不知道我应该看什么来纠正。

任何帮助表示赞赏。

<script type="text/javascript"><!--
function checkAge(f){
var dob=new Date();
var date=dob.getDate();
var month=dob.getMonth() + 1;
var year=dob.getFullYear();
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
var cmbday=parseInt(document.getElementById("cmbday").options[document.getElementById("cmbday").selectedIndex].value);
var cmbyear=parseInt(document.getElementById("cmbyear").options[document.getElementById("cmbyear").selectedIndex].value);

age=year-cmbyear;

if(cmbmonth>month){age--;}
else{if(cmbmonth==month && cmbday>=date){age--;}}

if(cmbmonth==0){alert("You must enter the month you were born in.");return false;}
else if(cmbday==0){alert("You must enter the day you were born on.");return false;}
else if(cmbyear==2005){alert("You must enter the year you were born in.");return false;}
else if(age<13){alert("You are unable to view this site!");location.replace("http://www.dharmatalks.org");return false;}
else{return true;}

}

// --></script>
4

1 回答 1

0

由于月份和年份长度的差异,以年、月和日为单位计算年龄比应该计算的要复杂一些。这是一个函数,它将以年、月、日、小时、分钟和秒的形式返回两个日期之间的差异。

function dateDifference(start, end) {

  // Copy date objects so don't modify originals
  var s = new Date(+start);
  var e = new Date(+end);
  var timeDiff, years, months, days, hours, minutes, seconds;

  // Get estimate of year difference
  years = e.getFullYear() - s.getFullYear();

  // Add difference to start, if greater than end, remove one year
  // Note start from restored start date as adding and subtracting years
  // may not be symetric
  s.setFullYear(s.getFullYear() + years);
  if (s > e) {
    --years;
    s = new Date(+start);
    s.setFullYear(s.getFullYear() + years);
  }
  // Get estimate of months
  months = e.getMonth() - s.getMonth();
  months += months < 0? 12 : 0;

  // Add difference to start, adjust if greater
  s.setMonth(s.getMonth() + months);
  if (s > e) {
    --months;
    s = new Date(+start);
    s.setFullYear(s.getFullYear() + years);
    s.setMonth(s.getMonth() + months);
  }


  // Get remaining time difference, round to next full second
  timeDiff = (e - s + 999) / 1e3 | 0;
  days     =  timeDiff / 8.64e4 | 0;
  hours    = (timeDiff % 8.64e4) / 3.6e3 | 0;
  minutes  = (timeDiff % 3.6e3) / 6e1 | 0;
  seconds  =  timeDiff % 6e1;

  return [years, months, days, hours, minutes, seconds];
}

您可以在年份部分之后缩写上述内容,如果您愿意,可以直接返回。

请注意,在您的代码中:

var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);

可:

var cmbmonth = document.getElementById("cmbmonth").value;

不需要parseInt, Date 构造函数将愉快地处理字符串值。如果您使用日历月份数字作为值(即 Jan = 1),则在将其提供给 Date 构造函数之前减去 1,但更简单地使用 javascript 月份索引作为值(即 Jan = 0)。

然后你可以这样做:

var diff = dateDifference(new Date(cmbyear, cmbmonth, cmbdate), new Date());
if (diff[0] < 18) {
  // sorry, under 18
}
于 2013-06-05T02:15:31.213 回答