-2

这是我在 StackOverflow 上的第一篇文章,我已经阅读了很多关于这个网站上的代码片段的页面,并且总是你给出很好的答案和建议..

但是现在我需要一些帮助。我想填充多个输入字段,我尝试在 JavaScript 中添加一个字段 ID,但到目前为止没有运气。

<script type="text/javascript">
<!--
function calculateAge(inputFieldId, outputFieldId, alert_18){

var age;

var input = document.getElementById(inputFieldId).value;

// Past date info

var pyear = parseInt(input.substring(6,10));
var pmonth = parseInt(input.substring(0,2)) - 1;
var pday = parseInt(input.substring(3,5));
// Today info
today = new Date();
year = today.getFullYear() ;
month = today.getMonth();
day = today.getDate();

if ( month < pmonth ){
age = year - pyear - 1;
}
else if ( month > pmonth ){
age = year - pyear;
}
else if ( month == pmonth ){
if ( day < pday ){
age = year - pyear - 1;
}
else if ( day > pday ){
age = year - pyear;
}
else if ( day == pday ){
age = year - pyear;
}
}
document.getElementById(outputFieldId).value = age;
document.getElementById(outputFieldId).value = age2;

if(alert_18 == 'true'){
if(age < 18){

//Customize alert message

alert('Attention: under 18!');
}
}
}
//-->
</script>

任何帮助将不胜感激

4

1 回答 1

0

我建议使用以下解决方案来处理任意数量的输出字段(并粗略计算年龄 - 不考虑闰年):

<script type="text/javascript">
<!--
function calculateAge(inputFieldId, outputFieldId, alert_18){
  var input = document.getElementById(inputFieldId).value,
      pyear = parseInt(input.substring(6,10)),
      pmonth = parseInt(input.substring(0,2)) - 1,
      pday = parseInt(input.substring(3,5)),
      dt1 = new Date(),
      dt2 = new Date(pyear, pmonth, pday),
      ageMs = dt2.getTime() - dt1.getTime(),
      age = parseInt(ageMs / 1000 / 60 / 60 / 24 / 365);


  if(outputFieldId instanceof Array) {
    for(var i = 0, l = outputFieldId.length; i < l; i++)
      document.getElementById(outputFieldId[i]).value = age;
  }
  else
    document.getElementById(outputFieldId).value = age; 

  if(alert_18 && age < 18) {
    //Customize alert message

    alert('Attention: under 18!');
  }
}
//-->
</script>

然后,当您调用它时,您可以将单个字符串作为 outputfieldid 传递,如下所示:

calculateAge("get-age", "calculated-age", true);

或者您可以像这样传递一个 fieldid 数组:

calculateAge("get-age", ["calculated-age1", "calculated-age2"], true);
于 2012-10-23T12:43:23.963 回答