首页 > 解决方案 > 使用 Javascript,如何比较 2 个值以查看它们是否可被彼此整除?

问题描述

我正在尝试在这里编写一个事件处理程序,以便当用户在第一个文本框和第二个文本框中输入一个数字并单击“比较值”按钮时,一个函数会执行并检查

如果其中一个数字为零,则在“box5”上打印,“您输入了零”

如果两个数字相同,则在“box5”上打印,“数字相同”

如果第一个数字可以被第二个整除,它会在“box5”上打印出来,“第一个可以被第二个整除”

如果第二个数字可以被第一个整除,它会在“box5”上打印出来,“第二个可以被第一个整除”

else-如果数字不相除,则打印在“box5”上,“它们不可除”

我已经为此创建了 HTML 页面,但我不知道应该如何处理。一些用户告诉我使用“keyup”方法,我希望如果有人可以向我展示他们将使用“keyup”方法处理此问题的方式的示例,如果可能的话。提前致谢

<p> Enter two numbers and we will tell you if they are evenly divisble
<p> Enter your first number:</p> <input type="text" id="box3">
<p> Enter your second number: </p> <input type="text" id="box4"> 
<button id="compareValue">Compare Values</button>
<p> Output will appear here: </p> <input text="type" id="box5" disabled>

我只是想创建一个简单的工具来比较用户输入的两个数字,并检查它们是否可整除,如果是,哪个数字可以被哪个整除,并确保没有输入零输入,否则 - 如果没有任何东西可以被彼此整除,那么它会告诉你它们不能被整除。

编辑:我忘了包括我的 JavaScript 尝试:

let firstNumber = document.getElementById("box3")
let secondNumber = document.getElementById("box4")
let outputNumber = document.getElementById("box5")

$(document).ready(function(){
$("compareValue").keyup(function(){
let a = firstNumber.value;
let b = secondNumber.value;
  if (a === 0 || b === 0);
    let outputNumber.value = "The Number is ZERO."
  });
  if (a % b );
    let outputNumber.value = "First number is divisible by the second number."
  });
  if (b % a);
    let outputNumber.value = "Second Number is divisble by the first number."
  });
  else-if (a !== b && b !== a);
    let outputNumber.value = "The numbers are not divisible."
  });
});

标签: javascriptjqueryhtmlobjectwebpage

解决方案


只需将%(modulus) 用于可除性和==测试相等性:

function compare() {
  var value1 = parseInt(document.getElementById("box3").value);
  var value2 = parseInt(document.getElementById("box4").value);
  var display = document.getElementById("box5");
  if (value1 == 0 || value2 == 0) {
    display.value = "You have entered zero";
  } else if (value1 == value2) {
    display.value = "The numbers are the same";
  } else if (value1 % value2 == 0) {
    display.value = "The first is divisible by the second";
  } else if (value2 % value1 == 0) {
    display.value = "The second is divisible by the first";
  } else {
    display.value = "They are not divisible";
  }
}
<p> Enter two numbers and we will tell you if they are evenly divisble</p>
<p> Enter your first number:</p> <input type="text" id="box3">
<p> Enter your second number: </p> <input type="text" id="box4">
<button id="compareValue" onclick="compare()">Compare Values</button>
<p> Output will appear here: </p> <input text="type" id="box5" disabled>


推荐阅读