输入数字并使用jquery查找最大和最小数字

时间:2019-03-28 18:24:35

标签: javascript jquery arrays typescript if-statement

<script type="text/javascript">
  function largest() {
    var num1, num2;
    num1 = Number(document.getElementById("N").value);
    num2 = Number(document.getElementById("M").value);
    if (num1 > num2) {
      window.alert(num1 + "-is largest");
    } else if (num2 > num1) {
      window.alert(num2 + "-is largest");
    }
</script>

1 个答案:

答案 0 :(得分:1)

如果我的理解正确,那么您想完成上面的代码,以便可以调用largest()函数来识别输入之间有id="N"id="M"的最大数字。 / p>

一种方法可能是引入一个<button>元素,并使用jQuery将一个click()处理程序绑定到该处理程序,该处理程序将像这样调用largest()

function largest() {
  var num1, num2;

  /* Update to use jQuery style selectors */
  num1 = Number($("#N").val());
  num2 = Number($("#M").val());

  if (num1 > num2) {
    window.alert(num1 + " from N is largest and " + num2 + " from M is lowest");
  } else if (num2 > num1) {
    window.alert(num2 + " from M is largest and " + num1 + " from N is lowest");
  }
}

/* Get the find-largest button, and add a click event listener which calls the
largest() function */
$("#find-largest").click(function() {

  /* Call the largest() function */
  largest();

  /* Prevent the buttons default behavior */
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>
<div>
  <label>Number N:</label>
  <input id="N" type="number" />
</div>
<div>
  <label>Number M:</label>
  <input id="M" type="number" />
</div>

<!-- Add a button which when clicked calls largest() function -->
<div>
  <button id="find-largest">Find largest</button>
</div>