选中的元素未定义

时间:2017-12-22 18:33:05

标签: javascript jquery input

尝试在CodePen中制作简单的乘法/除法程序,https://codepen.io/rynsp8/pen/PEGxpj

但每当我尝试将数字打印到控制台,甚至运行该功能时,它都没有给我任何帮助。我将空白打印到控制台,并给我一个0来传递给我的HTML。

var numberOne = document.getElementById("firstNumber").value;
var numberTwo = document.getElementById("secondNumber").value;

$('#multiply').click(function() {
  var product = numberOne * numberTwo;
  console.log(numberOne);
  return document.getElementById('answer').innerHTML = product;
})

$('#divide').click(function() {
  var dividend = numberOne / numberTwo;
  return document.getElementById('answer').innerHTML = dividend;
}) 

这是我的HTML

<div>
  <div id="container">
    <section id="numberInput">
      <input id="firstNumber" type="number" placeholder="Number 1">
      <input id="secondNumber" type="number" placeholder="Number 2">
    </section>
    <section id="buttonCTN">
      <button id="multiply" class="button">Multiply</button>
      <button id ="divide" class="button">Divide</button>
    </section>
    <section id="ansSEC">
      <p id="answer"></p>
    </section>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

var txtOne = document.getElementById("firstNumber");   
var txtTwo = document.getElementById("secondNumber");   

$('#multiply').click(function() {

var numberOne = txtOne.value;   //Now we can Get Updated value from textbox
var numberTwo = txtTwo.value;

var product = numberOne * numberTwo;
console.log(numberOne);
return document.getElementById('answer').innerHTML = product;
})

$('#divide').click(function() {

var numberOne = txtOne.value;   //Now we can Get Updated value from textbox
var numberTwo = txtTwo.value;

 var dividend = numberOne / numberTwo;
 return document.getElementById('answer').innerHTML = dividend;
}) 

您正在获取页面加载的值,此时文本框为空。单击事件值不会更新numberOne和numberTwo变量。您应该获得点击事件的值。