如何在队伍分数超过30时修改元素display属性?
解决分数达标后显示皇冠图片的问题
你的问题出在条件判断只执行了一次:页面加载时counthomePoints初始值为0,此时判断逻辑执行后把皇冠设为隐藏,但之后每次点击加分按钮更新分数时,并没有重新触发这个判断,所以即使分数超过29,皇冠也不会自动显示。
修复方案
把皇冠的显示逻辑封装成可复用的函数,每次分数变化(加分、重置)后调用这个函数,就能实时更新显示状态:
- 封装判断函数
function updateCrownDisplay() { // 主队皇冠:分数>29显示,否则隐藏 h.style.display = counthomePoints > 29 ? "block" : "none"; // 顺便处理客队皇冠(如果需要的话) g.style.display = countguestPoints > 29 ? "block" : "none"; }
- 在所有修改分数的函数末尾调用这个函数
比如加分函数:
function haddone() { counthomePoints += 1; homePoints.textContent = counthomePoints; updateCrownDisplay(); // 加分后更新皇冠状态 } function haddtwo() { counthomePoints += 2; homePoints.textContent = counthomePoints; updateCrownDisplay(); } // 同理,haddthree、gaddone、gaddtwo、gaddthree函数都要加上这一行
- 重置函数里也要调用,确保重置后皇冠隐藏
function res() { counthomePoints = 0; countguestPoints = 0; guestPoints.textContent = 0; homePoints.textContent = 0; updateCrownDisplay(); }
- 页面初始化时调用一次,确保初始状态正确
updateCrownDisplay();
完整修改后的代码
let homePoints = document.getElementById("homep"); let guestPoints = document.getElementById("guestp"); let counthomePoints = 0; let countguestPoints = 0; var h = document.getElementById("hw"); var g = document.getElementById("gw"); function updateCrownDisplay() { h.style.display = counthomePoints > 29 ? "block" : "none"; g.style.display = countguestPoints > 29 ? "block" : "none"; } function haddone() { counthomePoints += 1; homePoints.textContent = counthomePoints; updateCrownDisplay(); } function haddtwo() { counthomePoints += 2; homePoints.textContent = counthomePoints; updateCrownDisplay(); } function haddthree() { counthomePoints += 3; homePoints.textContent = counthomePoints; updateCrownDisplay(); } function gaddone() { countguestPoints += 1; guestPoints.textContent = countguestPoints; updateCrownDisplay(); } function gaddtwo() { countguestPoints += 2; guestPoints.textContent = countguestPoints; updateCrownDisplay(); } function gaddthree() { countguestPoints += 3; guestPoints.textContent = countguestPoints; updateCrownDisplay(); } function res() { counthomePoints = 0; countguestPoints = 0; guestPoints.textContent = 0; homePoints.textContent = 0; updateCrownDisplay(); } updateCrownDisplay();
内容的提问来源于stack exchange,提问作者NOIZOS NOIZOS
相关产品推荐
相关产品推荐

