document.getElementById
获取元素(即p标签)但是尽快获得
它写入内容消失。控制台上没有错误,但只要在p标签上写入任何内容,p标签中写入的内容就会消失。
我找不到任何理由它也不工作我也不允许使用php接受表单输入。
var d=new Date();
var cday=d.getDay();
var cmonth=d.getMonth();
var cyear=d.getFullYear();
var day,month,year,dage,mage,yage;
function getDOB() {
var DOB = new Date(document.getElementById("DOB").value);
year = DOB.getFullYear();
month = DOB.getMonth();
day = DOB.getDay();
}
document.getElementById("inp").onclick = function execute() {
getDOB();
yage = cyear - year;
if (cmonth >= month) {
mage = cmonth - month;
} else {
mage = 12 - (month - cmonth);
yage = yage - 1;
}
if (cday >= day) {
dage = cday - day;
} else {
mage = mage - 1
dage = 30 - (day - cday);
}
document.getElementById("output").innerHTML = "your age is " + dage + " days " + mage + " months " + yage + " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button id="inp">submit</button>
<br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>
答案 0 :(得分:2)
您的代码包含早期错误,但尚未达到innerHTML。
以下是错误:
未捕获的ReferenceError:未定义cyear
您还必须在函数末尾添加return false;
以阻止表单提交,如@thewatcheruatu所述。
答案 1 :(得分:0)
date=new Date(); // Get current date
cyear=date.getFullYear(); // current year
cmonth=date.getMonth()+1; // current month
cday=date.getDate(); // current day
function getDOB()
{
var DOB=new Date(document.getElementById("DOB").value);
year=DOB.getFullYear();
month=DOB.getMonth();
day=DOB.getDate(); // getDate() function returns the current date
}
function execute()
{
getDOB();
yage=cyear-year;
if( cmonth>=month)
{
mage=cmonth-month;
}
else
{
mage=12-(month-cmonth);
yage=yage-1;
}
if ( cday>=day )
{
dage=cday-day;
}
else
{
mage=mage-1
dage=30-(day-cday);
}
document.getElementById("output").innerHTML="your age is "+dage+" days "+mage+" months "+yage+ " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button type="button" id="inp" onclick="execute()">submit</button><br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>