PHP实现页面加载时随机展示不重复多词的问题求助
Solution: Display Multiple Non-Repeating Words on Page Load
Hey there! Let's get your page showing multiple unique words automatically when it loads. Here's a simple, reliable approach to fix your current issue:
Step 1: Set Up Your HTML Container
First, add a container in your HTML where the words will appear. Give it an ID so we can target it easily:
<div id="word-display-container"></div>
Step 2: Write the JavaScript Logic
We'll create a pool of words, pick a specified number of non-repeating ones at random, then insert them into the container. Here's the code you can drop into your project:
// Wait for the page to fully load before running the script document.addEventListener('DOMContentLoaded', function() { // Replace this array with your own vocabulary list const wordPool = ["Serendipity", "Ephemeral", "Luminescence", "Quintessential", "Melancholy"]; // Adjust this number to set how many unique words you want to display const numberOfWordsToShow = 3; // Create a copy of the word pool to avoid modifying the original list let availableWords = [...wordPool]; let selectedWords = []; // Pick non-repeating words until we reach the desired count for (let i = 0; i < numberOfWordsToShow; i++) { if (availableWords.length === 0) break; // Stop if we run out of unique words const randomIndex = Math.floor(Math.random() * availableWords.length); selectedWords.push(availableWords[randomIndex]); // Remove the selected word from the pool to prevent repeats availableWords.splice(randomIndex, 1); } // Render the selected words into the container const displayContainer = document.getElementById('word-display-container'); selectedWords.forEach(word => { const wordElement = document.createElement('span'); wordElement.textContent = word; // Add basic spacing between words (customize style as needed) wordElement.style.marginRight = '18px'; wordElement.style.fontSize = '1.2rem'; displayContainer.appendChild(wordElement); }); });
How This Works
DOMContentLoaded: Makes sure the script runs only after the page's HTML is fully loaded, so we can reliably find the display container.- Word Pool Copy: We duplicate your original word list so we don't alter it—keeping the full list intact for future use.
- No Repeats Guarantee: Each time we pick a word, we remove it from the available pool using
splice(), so it can't be selected again. - Flexible Rendering: We use
<span>elements for each word (you can switch to<div>or other tags if you want stacked words) and add basic styling for readability.
Quick Customization Tips
- Change
numberOfWordsToShowto adjust how many words appear on load. - Update the
wordPoolarray with your own set of vocabulary. - Tweak the inline styles (like
marginRight,fontSize, orcolor) to match your site's design. - If you prefer ordered words instead of random, skip the
randomIndexlogic and just take the first N words from the pool.
内容的提问来源于stack exchange,提问作者Berta Nicolau
相关产品推荐
相关产品推荐

