如何为句子数组添加链接?附按钮切换句子的现有代码
How to Add Clickable Links to Sentences in Your Rotating Array
Got it, let's get this sorted for you! The core idea here is that innerHTML will parse and render HTML content, so we can easily add clickable links to specific entries in your sentence array. Below are two straightforward solutions depending on your needs:
Approach 1: Use HTML Strings Directly in the Array
This is the simplest method if you only have a few sentences that need links. Just write the sentence as an <a> tag directly in your array:
let cnt = 0; function callMe() { // Update the array to include a link for sentence3 (use your internal page path here) const Your_Sentences_Array = [ 'sentence0', 'sentence1', 'sentence2', '<a href="/your-target-page" target="_self">sentence3 (Click to navigate)</a>' ]; const div = document.getElementById('idtxt'); div.innerHTML = Your_Sentences_Array[cnt]; // Reset counter when we reach the end, otherwise increment cnt = cnt === Your_Sentences_Array.length - 1 ? 0 : cnt + 1; }
Your existing HTML stays exactly the same:
<div class="game"> <div dir="rtl" class="sentence" id="idtxt"> sentence </div> <button class="done" type="button" onclick="callMe()">Done!</button> </div>
Approach 2: Use an Array of Objects (More Maintainable)
If you anticipate adding more links or customizing sentences later, using an array of objects will make your code cleaner and easier to scale. Each object holds the sentence text and optional link:
let cnt = 0; // Store each sentence with optional link data const Your_Sentences_Array = [ { text: 'sentence0' }, { text: 'sentence1' }, { text: 'sentence2' }, { text: 'sentence3 (Click to navigate)', link: '/your-target-page' } ]; function callMe() { const div = document.getElementById('idtxt'); const currentSentence = Your_Sentences_Array[cnt]; // Generate HTML based on whether a link exists if (currentSentence.link) { div.innerHTML = `<a href="${currentSentence.link}" target="_self">${currentSentence.text}</a>`; } else { div.innerHTML = currentSentence.text; } // Update counter with cleaner syntax cnt = (cnt >= Your_Sentences_Array.length - 1) ? 0 : cnt + 1; }
Quick Notes:
- Use
target="_self"to open the link in the same tab, ortarget="_blank"for a new tab (addrel="noopener noreferrer"with_blankto keep your site secure). - If your sentence content comes from user input, avoid raw
innerHTML—sanitize the content first to prevent XSS attacks.
内容的提问来源于stack exchange,提问作者nirshh5
相关产品推荐
相关产品推荐

