如何用JavaScript实现两数整除校验工具(含keyup示例)
First, let's fix a tiny typo in your HTML first—your output input has the type attribute written backwards:
<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">Compare Values</button> <p> Output will appear here: </p> <!-- Fixed the type attribute here --> <input type="text" id="box5" disabled>
Now, let's tackle the JavaScript. Your original code had a few syntax and logic issues (like incorrect selectors, misplaced semicolons, and not converting input strings to numbers). We'll implement the keyup method as requested—this will let the comparison run automatically as the user types, plus we'll keep the button click functionality for convenience.
First, make sure you've included jQuery in your page (add this right before your closing </body> tag if you haven't):
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
Here's the corrected JavaScript:
$(document).ready(function() { // Get references to our elements const $firstNum = $("#box3"); const $secondNum = $("#box4"); const $output = $("#box5"); // Create a reusable function to handle the comparison logic function compareNumbers() { // Convert input values to numbers (parseFloat handles decimals, parseInt for integers) const a = parseFloat($firstNum.val()); const b = parseFloat($secondNum.val()); // First, check if either input is empty or not a number if (isNaN(a) || isNaN(b)) { $output.val("Please enter valid numbers"); return; } // Now run through your comparison conditions in order if (a === 0 || b === 0) { $output.val("You have entered zero"); } else if (a === b) { $output.val("The numbers are the same"); } else if (b !== 0 && a % b === 0) { // Ensure we don't divide by zero $output.val("The first is divisible by the second"); } else if (a !== 0 && b % a === 0) { $output.val("The second is divisible by the first"); } else { $output.val("They are not divisible"); } } // Bind keyup event to both input boxes to run comparison as user types $firstNum.keyup(compareNumbers); $secondNum.keyup(compareNumbers); // Bind click event to the button for manual trigger $("#compareValue").click(compareNumbers); });
Key Fixes & Explanations:
- Selector Corrections: Used
$("#elementId")for proper jQuery ID selection (your original code missed the#for the button). - Number Conversion: Converted input values from strings to numbers with
parseFloat—this is critical because input values are always strings, and comparing strings directly would cause bugs. - Reusable Function: Created a single
compareNumbersfunction to avoid code duplication, which we can call from bothkeyupandclickevents. - Condition Order: Followed your exact requirement order (check for zero first, then equality, then divisibility) to ensure correct behavior.
- Edge Case Handling: Added a check for non-numeric inputs, and made sure we never divide by zero (since dividing by zero would throw an error).
- Syntax Fixes: Removed misplaced semicolons after
ifstatements, fixedelse-iftoelse if, and corrected scope issues with variables.
This implementation will update the output box in real-time as the user types (thanks to keyup) and also work when clicking the "Compare Values" button.
内容的提问来源于stack exchange,提问作者user10326981

