javascript - 使用 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."
});
});
解决方案
只需将%
(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>
推荐阅读
- here-api - HERE Maps Intermodal Routing API v8 示例不起作用(API 密钥验证)
- python - 如何计算列表中的项目出现次数,如果它不在列表中,则返回零计数?
- assembly - NASM 获取系统时间
- ios - SwiftUI 因一位用户的 EXC_BREAKPOINT (SIGTRAP) 而崩溃,我无法在模拟器中复制它
- powerquery - Excel PowerQuery 中的 IF AND OR
- r - plot_ly 具有常量变量的 3D 图
- javascript - v-model 没有正确绑定到对象数组
- sql-server - SQL Server:更改跟踪可以忽略更改为相同值的字段吗?
- python - python & GPIO 脚本
- firebase - 在 Firestore 中使用 runTransaction 方法的同时写入操作不起作用