点击评分按钮后内容显示Undefined的前端问题解决咨询
解决评分提交后显示"You selected Undefined out of 5"的问题
问题根源
- 你在初始化
thankYouCard时就固定了它的HTML内容,此时number还未被赋值,默认是undefined,后续点击评分修改number不会自动同步到已经生成的DOM元素里。 - HTML代码里的提交按钮标签写错了:
<button id="submit">Submit</div>应该改为<button id="submit">Submit</button>,错误的闭合标签会导致DOM结构异常。
修正方案一:提交时动态生成感谢卡片
这种方式简单直接,在用户点击提交时再生成感谢卡片的内容,确保使用最新的number值:
const cardContainer = document.querySelector('.card-container') const submitButton = document.querySelector('#submit') const ratingButtons = document.querySelectorAll('.rating') let number; ratingButtons.forEach(el => { el.addEventListener('click', e => { number = e.target.textContent.trim() // 去除文本可能存在的空格 console.log(number); }) }) function submit() { // 提交时才生成感谢卡片内容 const thankYouCard = document.createElement('div') thankYouCard.innerHTML = ` <div id="annoucement">You selected ${number || 'no'} out of 5</div> <header>Thank you!</header> <main id="thank-you">We appreciate you taking the time to give a rating. If you ever need more support, don't hesitate to get in touch! </main>` cardContainer.innerHTML = '' cardContainer.appendChild(thankYouCard) } submitButton.addEventListener('click', submit)
修正后的HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Frontend Mentor | Interactive rating component</title> </head> <body> <!-- Rating state start --> <div class="card-container"> <header>How did we do?</header> <main> Please let us know how we did with your support request. All feedback is appreciated to help us improve our offering!</main> <div id="rating-container"> <button class="rating">1</button> <button class="rating">2</button> <button class="rating">3</button> <button class="rating">4</button> <button class="rating">5</button> </div> <button id="submit">Submit</button> </div> <script> </script> </body> </html>
修正方案二:提前创建DOM,仅更新需要变化的文本
如果希望提前构建好感谢卡片的DOM结构,只在点击评分时更新评分数值,可以这样写:
const cardContainer = document.querySelector('.card-container') const submitButton = document.querySelector('#submit') const thankYouCard = document.createElement('div') const ratingButtons = document.querySelectorAll('.rating') let number; // 提前构建DOM,把评分数值的位置留出来 thankYouCard.innerHTML = ` <div id="annoucement">You selected <span id="rating-value"></span> out of 5</div> <header>Thank you!</header> <main id="thank-you">We appreciate you taking the time to give a rating. If you ever need more support, don't hesitate to get in touch! </main>` // 获取用于显示评分的元素 const ratingValueEl = thankYouCard.querySelector('#rating-value') ratingButtons.forEach(el => { el.addEventListener('click', e => { number = e.target.textContent.trim() ratingValueEl.textContent = number // 点击时直接更新评分文本 console.log(number); }) }) function submit() { cardContainer.innerHTML = '' cardContainer.appendChild(thankYouCard) } submitButton.addEventListener('click', submit)
内容的提问来源于stack exchange,提问作者Billee_efsa
相关产品推荐
相关产品推荐

