我是java脚本的新手,并且正在使用年龄计算器。我做了一个我发现工作得很好但我注意到你要使用它,你必须刷新页面再次使用它。我怎么能这样做你不需要刷新,你只需输入另一个值?
<table id="tableCenter">
<tr id="yearBornRow">
<p>What year were they born?</p>
<input id="yearBorn">
</tr>
<tr id="currentYearRow">
<p>What is the current year?</p>
<input id="currentYear">
</tr>
</table>
<br>
<button onclick="showAge()">Submit</button>
<p id="printCurrentAge">Submit to find the age!</p>
然后是js
<script>
var yearBorn = document.getElementById("yearBorn").value
var currentYear = document.getElementById("currentYear").value
var age = currentYear - yearBorn
var possiblity = age++
function showAge(){
document.getElementById("printCurrentAge").innerHTML = "The person is either " +possiblity+ " or " +age;
}
</script>
感谢先进的任何帮助
答案 0 :(得分:3)
由于您使用值执行算术运算,因此需要将它们正确地解析为整数,以便通过parseInt()
函数使用它们:
var yearBorn = parseInt(document.getElementById("yearBorn").value);
var currentYear = parseInt(document.getElementById("currentYear").value);
var age = currentYear - yearBorn
var possiblity = age + 1;
您还需要在showAge()
函数中添加它,以便每次单击按钮时计算它:
function showAge(){
var yearBorn = parseInt(document.getElementById("yearBorn").value);
var currentYear = parseInt(document.getElementById("currentYear").value);
var age = currentYear - yearBorn
var possiblity = age + 1;
document.getElementById("printCurrentAge").innerHTML = "The person is either " +possiblity+ " or " +age;
}
答案 1 :(得分:0)
您需要在函数内部移动变量。它会像魅力一样工作!!如下所示:
<script>
function showAge(){
var yearBorn = document.getElementById("yearBorn").value
var currentYear = document.getElementById("currentYear").value
var age = currentYear - yearBorn
var possiblity = age++
document.getElementById("printCurrentAge").innerHTML = "The person is either " +possiblity+ " or " +age;
}
</script>