<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>if...else</title>
<style>
.con{
width:100px;
high:20px;
}
</style>
<script type="text/JavaScript">
function rec()
{
var myage ="rec";//赵红的年龄为99
myage=45;
if(myage<=44)
{ document.write("青年");}
else if(myage<=59)
{document.write("中年人");}
else if(myage<=89)
{document.write("老年人");}
else
{document.write("长寿老年人");}}
</script>
</head>
<body>
<input class="con" name="button" type="number" value=""/><br>
<input name="button" type="button" onClick="rec()" value="请输出你的年龄" />
</body>
</html>
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>年龄-结果</title> </head> <body> <span>年龄:</span> <input id="t2"><br> <button onclick="pd()">判断</button> <input id="t1"> </body> <script type="text/JavaScript"> var tt1=document.getElementById("t1"); var n1="青年"; var n2="中年人"; var n3="老年人"; var n4="长寿老年人"; var n="年龄阶段为:"; function pd(){ var nt="未判断";//但是空白默认为0,乱填显示这个 var myage =document.getElementById("t2").value; //赵红的年龄为 输入框t2 if(myage<=44) {nt=n1;} else if(myage<=59) {nt=n2;} else if(myage<=89) {nt=n3;} else if(myage>=90) {nt=n4;} tt1.value=n+nt; } </script> </html>
在rec()方法中定义了常量【myage=45;】的话,那么调用rec()方法时就一直取的45这个常量。
重点:我们需要获取从文本框中用户输入的值,动态判断:
获取表单的实现代码:var myage = document.getElementById("age").value;
参考代码:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>if...else</title> <style> .con{ width:100px; high:20px; } </style> </head> <body> <input id="age" class="con" name="button" type="number"/><br> <input name="button" type="button" onClick="rec()" value="请输出你的年龄" /> <p id="show"></p> </body> <script type="text/JavaScript"> function rec(){ var myage = document.getElementById("age").value; if(myage>=0&&myage<=44) { document.getElementById("show").innerHTML = "青年";} else if(myage>44&&myage<=59) {document.getElementById("show").innerHTML = "中年人";} else if(myage>=59&&myage<=89) {document.getElementById("show").innerHTML = "老年人";} else {document.getElementById("show").innerHTML = "长寿老年人";} }</script> </html>
怎么让他在表单里直接输入年龄后显示