使用$(document).ready()时页面无法加载,Etch-a-Sketch JS功能实现遇阻
Hey there! Let's work through getting your Etch-a-Sketch up and running—this is such a classic fun project, so let's iron out the kinks step by step.
1. First: Confirm jQuery is Properly Loaded
If your page isn't loading right or $(document).ready() isn't firing, the most common issue is that jQuery isn't being imported before your custom code.
Make sure you have a jQuery script tag before your own JavaScript in the <head> or at the end of <body>:
<!-- Place this BEFORE your custom JS --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="your-etch-a-sketch-code.js"></script>
If you see $ is not defined in your browser's console (F12 > Console tab), that's the exact problem—fix the import order and you'll be halfway there.
2. Fix the $(document).ready() Structure
Double-check that all your Etch-a-Sketch logic lives inside the ready function. It's easy to accidentally place code outside, which will run before the DOM is fully loaded:
// Correct structure $(document).ready(function() { // Initialize grid on page load generateGrid(16); // Bind refresh button click $('#refresh-btn').click(function() { handleGridRefresh(); }); }); // Helper functions can live outside, but make sure they're defined before use function generateGrid(size) { // Grid generation code here }
You can also use the shorter (and equivalent) syntax if you prefer:
$(function() { // Same as $(document).ready() });
3. Fix Grid Generation Logic
Let's build a reliable grid generator that clears old grids and creates uniform squares. First, make sure you have a container in your HTML:
<div id="sketch-container"></div> <button id="refresh-btn">Resize Grid</button>
Then update your generateGrid function to properly create and style the grid:
function generateGrid(size) { const container = $('#sketch-container'); // Clear existing grid first (critical for refresh!) container.empty(); // Set up CSS Grid layout for uniform squares container.css({ 'display': 'grid', 'grid-template-columns': `repeat(${size}, 1fr)`, 'grid-template-rows': `repeat(${size}, 1fr)`, 'width': '500px', // Fixed size keeps squares square 'height': '500px', 'gap': '1px' // Optional: Adds space between squares }); // Create size x size squares for (let i = 0; i < size * size; i++) { const square = $('<div class="sketch-square"></div>'); square.css({ 'background-color': '#ffffff', 'border': '1px solid #eeeeee' }); container.append(square); } // Bind hover effect AFTER generating squares bindHoverColorChange(); }
4. Fix Mouse Hover Color Change
Since squares are generated dynamically, you can't just bind hover() directly on page load—use event delegation to listen for hover events on the container's child squares, or bind the event right after creating each square. Here's the delegation method (more efficient for large grids):
function bindHoverColorChange() { $('#sketch-container').on('mouseenter', '.sketch-square', function() { // Use a fixed color or randomize it! $(this).css('background-color', getRandomColor()); }); } // Optional: Add a random color function for extra fun function getRandomColor() { const hexChars = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += hexChars[Math.floor(Math.random() * 16)]; } return color; }
5. Fix the Refresh Button Functionality
Add validation to ensure users enter a valid number, and call generateGrid with the new size:
function handleGridRefresh() { const newSize = prompt('Enter new grid size (1-100 recommended):'); const parsedSize = parseInt(newSize); // Validate input to avoid errors if (!isNaN(parsedSize) && parsedSize > 0 && parsedSize <= 100) { generateGrid(parsedSize); } else { alert('Please enter a valid number between 1 and 100!'); } }
6. Debug with Browser Dev Tools
If something still isn't working, open your browser's Dev Tools (F12) and check the Console tab for errors. Syntax mistakes (like missing brackets or misspelled variable names) will show up here, and they're often the root cause of "page not loading" issues.
内容的提问来源于stack exchange,提问作者jam_arcus

