如何将html输入绑定到我的javascript函数中?

时间:2016-01-31 13:54:50

标签: javascript html

<!DOCTYPE html>
<html>


    <body>
        <form>
            Birth Year:<br>
            <input type="number" name="birthYear">
            <br>
            Current Year:<br>
            <input type="number" name="currentYear">
        </form>
        <button onclick="calculateAge()">Calculate Age</button>
        <div id="output"></div>

          <script>
          function calculateAge(ghF, xhF) {
          var ghF = "birthYear"
          var xhF = "currentYear"
          return (xhF - ghF);
          } {
           document.getElementByID("output").innerHTML = text;
          };
          </script>
   </body>

当我点击按钮时,它应该打印出来&#34;你是x岁&#34;。我会在哪里添加该文字?当我点击按钮时,没有任何反应。

3 个答案:

答案 0 :(得分:0)

  

takeWhille将返回带有getElementById的DOM元素,如上所述。 id.value元素的属性,它将赋予input的值    您必须在进行减法后设置input,而不是返回值。

注意:您必须为元素分配唯一的innerHTML/innerText属性才能检索DOM元素。

&#13;
&#13;
id
&#13;
function calculateAge() {
  var ghF = document.getElementById("birthYear").value;
  var xhF = document.getElementById("currentYear").value;
  document.getElementById("output").innerHTML = xhF - ghF;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

function calculateAge() {
          var ghF = document.getElementById("birthYear").value;
          var xhF = document.getElementById("currentYear").value;
 document.getElementById("output").innerHTML="You are " +(xhF - ghF) + " age";
          }    

EXAMPLE

答案 2 :(得分:0)

功能糟糕。

这样可以解决问题:

  function calculateAge() {
        var ghF = document.querySelector('[name="birthYear"]').value;
        var xhF = document.querySelector('[name="currentYear"]').value;
        document.getElementById("output").innerHTML = "You are "+(xhF - ghF)+" age";
    }
<form>
    Birth Year:
    <br>
    <input type="number" name="birthYear">
    <br>
    Current Year:
    <br>
    <input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>