使用jQuery对比点击选中按钮文本与隐藏元素文本(动态生成元素场景)
Got it, let's tackle this problem step by step! Since your .list-group divs are dynamically generated, we need to use event delegation to make sure the click handlers work even for elements added after the page loads. Here's a practical, reliable implementation:
First, let's align on the core goal: when a visible button in a .list-group is clicked, we compare its text with the hidden answer button's text in the same group, then show the result in the associated <p> element.
Step 1: Refine the HTML Structure (for easier targeting)
Even with dynamic generation, adding consistent classes to elements will make your code more maintainable. Adjust your generated HTML to include these classes:
<div class="list-group" id="id1"> <button class="option-btn">text1</button> <button class="option-btn">text2</button> <button class="option-btn">text3</button> <button class="option-btn">text4</button> <button class="answer-btn" style="display:none;">answer</button> <p class="result">Display the result</p> </div> <div class="list-group" id="id2">...</div>
Classes like option-btn, answer-btn, and result let us target elements reliably, no matter when they're added to the DOM.
Step 2: JavaScript Implementation (Event Delegation FTW)
Directly binding click events to dynamic buttons won't work—they don't exist when the page first loads. Instead, we'll attach the listener to a static parent (like document) and check if the clicked element is an option button.
Here's the code:
// Listen for clicks anywhere on the page document.addEventListener('click', function(e) { // Only act if the clicked element is an option button if (e.target.classList.contains('option-btn')) { // Find the closest parent list group to scope our actions const parentGroup = e.target.closest('.list-group'); if (!parentGroup) return; // Exit if no valid parent found // Get text content (trim to avoid accidental whitespace mismatches) const selectedText = e.target.textContent.trim(); const answerText = parentGroup.querySelector('.answer-btn').textContent.trim(); const resultDisplay = parentGroup.querySelector('.result'); // Compare and update the result if (selectedText === answerText) { resultDisplay.textContent = 'Correct! 🎉'; resultDisplay.style.color = 'green'; } else { resultDisplay.textContent = `Oops, wrong answer. The correct one is: ${answerText}`; resultDisplay.style.color = 'red'; } } });
Key Details to Note:
- Event Delegation: By attaching the listener to
document, we ensure it works for every.option-btn—even those added dynamically later. - Scoped Actions:
closest('.list-group')makes sure we only interact with elements in the same group as the clicked button, so results don't mix between differentid1,id2, etc. - Whitespace Handling:
.trim()removes extra spaces/newlines that might break the text comparison (super common with dynamically generated content!).
Testing with Dynamic Content
If you're generating .list-group divs via JavaScript, this code will still work perfectly. Here's an example of dynamic generation that pairs with our handler:
// Example function to add a new list group dynamically function createNewListGroup(groupId, optionsArray, correctAnswer) { const container = document.body; // Replace with your target container const newGroup = document.createElement('div'); newGroup.className = 'list-group'; newGroup.id = `id${groupId}`; // Add option buttons optionsArray.forEach(option => { const btn = document.createElement('button'); btn.className = 'option-btn'; btn.textContent = option; newGroup.appendChild(btn); }); // Add hidden answer button const answerBtn = document.createElement('button'); answerBtn.className = 'answer-btn'; answerBtn.textContent = correctAnswer; answerBtn.style.display = 'none'; newGroup.appendChild(answerBtn); // Add result paragraph const resultPara = document.createElement('p'); resultPara.className = 'result'; resultPara.textContent = 'Display the result'; newGroup.appendChild(resultPara); container.appendChild(newGroup); } // Usage: Create a new group with sample options createNewListGroup(3, ['cat', 'dog', 'bird'], 'dog');
This will work seamlessly with the click handler we wrote—no extra setup needed!
内容的提问来源于stack exchange,提问作者rajshekar

