当计数变量为0时隐藏对应span元素的前端实现问题
问题与解决方案
我试过网上多种解决方案都没生效,可能是操作有误或场景特殊。目前我通过span的ID统计页面中特定类div的数量,代码运行正常,但希望当统计数值为0时隐藏对应的span。页面里有多个同class、不同ID的span,分别对应不同div类的统计结果。
现有实现代码
JavaScript 代码
var numNew = $('.new').length; document.getElementById('numNewOutput').innerHTML = numNew; var numNewfilm = $('.newfilm').length; document.getElementById('numNewfilmOutput').innerHTML = numNewfilm; var numNewnonfictionfilm = $('.newnonfictionfilm').length; document.getElementById('numNewnonfictionfilmOutput').innerHTML = numNewnonfictionfilm; var numNewepisode = $('.newepisode').length; document.getElementById('numNewepisodeOutput').innerHTML = numNewepisode; var numNewnonfictionepisode = $('.newnonfictionepisode').length; document.getElementById('numNewnonfictionepisodeOutput').innerHTML = numNewnonfictionepisode; var numNewshort = $('.newshort').length; document.getElementById('numNewshortOutput').innerHTML = numNewshort;
对应HTML结构
<tr style="color:var(--new);"><td><span class="tallynum" id="numNewOutput"></span></td><td class="tallyhead">NEW</td></tr> <tr style="color:var(--new);"><td><span class="tallynum" id="numNewfilmOutput"></span></td><td class="tallyname">films</td></tr> <tr style="color:var(--new);"><td><span class="tallynum" id="numNewnonfictionfilmOutput"></span></td><td class="tallyname">nonfiction films</td></tr> <tr style="color:var(--new);"><td><span class="tallynum" id="numNewepisodeOutput"></span></td><td class="tallyname">episodes</td></tr> <tr style="color:var(--new);"><td><span class="tallynum" id="numNewnonfictionepisodeOutput"></span></td><td class="tallyname">nonfiction episodes</td></tr> <tr style="color:var(--new);"><td><span class="tallynum" id="numNewshortOutput"></span></td><td class="tallyname">shorts</td></tr>
有效解决方案
把重复的统计逻辑封装成函数,既减少冗余代码,又统一处理显示/隐藏逻辑:
核心代码
// 封装统计与显示逻辑的函数 function updateTally(targetClass, outputId) { const count = $(`.${targetClass}`).length; const outputElement = document.getElementById(outputId); // 设置统计数值 outputElement.innerHTML = count; // 数值为0时隐藏span,否则显示 outputElement.style.display = count === 0 ? 'none' : 'inline'; } // 批量处理所有统计项 updateTally('new', 'numNewOutput'); updateTally('newfilm', 'numNewfilmOutput'); updateTally('newnonfictionfilm', 'numNewnonfictionfilmOutput'); updateTally('newepisode', 'numNewepisodeOutput'); updateTally('newnonfictionepisode', 'numNewnonfictionepisodeOutput'); updateTally('newshort', 'numNewshortOutput');
可选扩展
如果需要隐藏整个统计行(而非仅span),修改函数中的隐藏逻辑:
function updateTally(targetClass, outputId) { const count = $(`.${targetClass}`).length; const outputElement = document.getElementById(outputId); const parentRow = outputElement.closest('tr'); outputElement.innerHTML = count; // 隐藏/显示整个表格行 parentRow.style.display = count === 0 ? 'none' : 'table-row'; }
注意事项
确保代码在DOM完全加载后执行,可包裹在jQuery的就绪事件中:
$(document).ready(function() { // 上述函数与调用代码放在此处 });
内容的提问来源于stack exchange,提问作者Rubbersquare
相关产品推荐
相关产品推荐

