求助:点击按钮在随机位置展示指定词汇的JavaScript实现
Fixing Your Random Word Display Code
Hey there! Let's break down what's going wrong with your modified code and get it working exactly how you want it.
Issues in Your Current Code
- You defined the
getRandomWordfunction but never called it inside your submit handler—so it never runs at all! - You're assigning the entire
wordsarray directly toelem.textContent, which would displayHello,No,Hi,Banana,Appleinstead of a single random word from the list. - There are syntax errors: your submit handler function isn't closed properly, and the
getRandomWordfunction also lacks a closing}. - Since you don't need user input anymore, using a form submit is overcomplicated—we can simplify this to a regular button for cleaner logic.
Fixed Code
First, update your HTML to use a simple button (no need for a text input now):
<button id="displayWordBtn">Show Random Word</button>
Then here's the corrected JavaScript:
$(document).ready(function() { // Define your word list once (outside the click handler for efficiency) const words = ['Hello', 'No', 'Hi', 'Banana', 'Apple']; // Get the button element const wordBtn = document.getElementById('displayWordBtn'); // Function to pick a random word from the list function getRandomWord() { const randomIndex = Math.floor(Math.random() * words.length); return words[randomIndex]; } // Add click event listener to the button wordBtn.addEventListener('click', function() { const fullWidth = window.innerWidth; const fullHeight = window.innerHeight; const randomWord = getRandomWord(); // Create the div element for the word const elem = document.createElement('div'); elem.textContent = randomWord; elem.style.position = 'absolute'; // Subtract the element's width/height so it doesn't go off-screen elem.style.left = Math.round(Math.random() * (fullWidth - elem.offsetWidth)) + 'px'; elem.style.top = Math.round(Math.random() * (fullHeight - elem.offsetHeight)) + 'px'; document.body.appendChild(elem); }); });
Key Improvements Explained
- Proper Random Word Selection:
Math.floor(Math.random() * words.length)gives us a valid index for thewordsarray, so we pick one random word each time the button is clicked. - Simpler Event Handling: Using a button click instead of form submit removes the need to prevent default form behavior, making the code easier to follow.
- Syntax Fixes: All functions and callbacks are properly closed, so the code runs without errors.
- Prevent Off-Screen Words: I added
elem.offsetWidthandelem.offsetHeightto the position calculation—this ensures the entire word stays visible on the screen instead of getting cut off at the edges.
Give this a try, and it should work exactly as you want: click the button, and a random word from your predefined list appears in a random spot on the page!
内容的提问来源于stack exchange,提问作者Milla F
相关产品推荐
相关产品推荐

