You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现网页端FizzBuzz算法的输入与结果展示

Interactive FizzBuzz Web Implementation

Got it, let's turn your console-based FizzBuzz into a web interactive tool! Here's a complete, working solution that ties your existing logic to HTML elements and displays results directly on the page:

Step 1: Full Working Code

This includes the UI elements, modified FizzBuzz logic, and interactivity all in one file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Interactive FizzBuzz</title>
    <style>
        /* Optional: Clean up the look a bit */
        .fizzbuzz-wrapper {
            max-width: 600px;
            margin: 3rem auto;
            padding: 0 1.5rem;
            font-family: Arial, sans-serif;
        }
        #results-area {
            margin-top: 2rem;
            padding: 1.2rem;
            background-color: #f8f9fa;
            border-radius: 6px;
            line-height: 1.8;
        }
        .fizz { color: #27ae60; font-weight: 600; }
        .buzz { color: #2980b9; font-weight: 600; }
        .fizzbuzz { color: #e74c3c; font-weight: 700; }
        input, button {
            padding: 0.5rem 1rem;
            font-size: 1rem;
            margin-right: 0.5rem;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        button {
            background-color: #3498db;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background-color: #2980b9;
        }
    </style>
</head>
<body>
    <div class="fizzbuzz-wrapper">
        <h2>FizzBuzz Web Tool</h2>
        <input type="number" id="number-input" placeholder="Enter a number (e.g., 20)" min="1">
        <button id="run-btn">Generate FizzBuzz</button>
        <div id="results-area"></div>
    </div>

    <script>
        // Modified FizzBuzz function: collects results instead of logging to console
        function getFizzBuzzResults(num) {
            const output = [];
            for (let i = 1; i <= num; i++) { 
                if (i % 3 === 0 && i % 5 === 0) { 
                    output.push('<span class="fizzbuzz">FizzBuzz</span>'); 
                } else if (i % 3 === 0) { 
                    output.push('<span class="fizz">Fizz</span>'); 
                } else if (i % 5 === 0) { 
                    output.push('<span class="buzz">Buzz</span>'); 
                } else { 
                    output.push(i.toString()); 
                } 
            }
            return output.join(', ');
        }

        // Add interactivity to the button
        document.getElementById('run-btn').addEventListener('click', function() {
            const inputField = document.getElementById('number-input');
            const resultsArea = document.getElementById('results-area');
            const userInput = parseInt(inputField.value);

            // Validate the input first
            if (isNaN(userInput) || userInput < 1) {
                resultsArea.innerHTML = '<strong>Oops! Please enter a valid positive number.</strong>';
                return;
            }

            // Generate and display the results
            const fizzBuzzOutput = getFizzBuzzResults(userInput);
            resultsArea.innerHTML = fizzBuzzOutput;
        });

        // Optional: Let users press Enter to run the function
        document.getElementById('number-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('run-btn').click();
            }
        });
    </script>
</body>
</html>

Key Changes & Breakdown

  • Modified FizzBuzz Logic: Instead of console.log, we collect results in an array and return them as a formatted string (with CSS classes for color coding).
  • Input Validation: We check if the user entered a valid positive number to avoid errors from non-numeric or negative inputs.
  • Event Listeners: The button click (and Enter key press) triggers the calculation, fetches the input value, runs the function, and inserts results into the page's results container.
  • Basic Styling: Added simple CSS to make the UI clean and results easier to read, with distinct colors for Fizz, Buzz, and FizzBuzz.

How to Use

  1. Copy this code into a new file named fizzbuzz.html.
  2. Open it in any web browser.
  3. Type a positive number into the input box.
  4. Click "Generate FizzBuzz" (or press Enter) to see the results displayed below.

This keeps your original FizzBuzz logic intact while adding the web interactivity you need!

内容的提问来源于stack exchange,提问作者siddhant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:00:43