使用标签名统计元素时计数不准确问题求助
修复ZenDesk页面中“¤”字符的精确计数问题
问题根源
原代码的核心缺陷是统计包含目标字符的DOM元素数量,而非字符本身的总出现次数。比如父元素的textContent会包含所有子元素的文本内容,只要子元素里有“¤”,父元素也会被计入统计,导致重复计数,结果远大于实际字符数。
修正后的解决方案
方案1:全局文本统计(最简单精准)
直接提取页面所有可见文本,统计目标字符的总出现次数:
function findOccurrences(char) { // 获取页面全部可见文本内容 const fullText = document.body.textContent; // 转义特殊字符,避免正则匹配出错 const escapedChar = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 全局匹配所有目标字符 const matches = fullText.match(new RegExp(escapedChar, 'g')); // 返回匹配数量,无匹配则返回0 return matches ? matches.length : 0; }
方案2:遍历可见文本节点(排除隐藏文本)
如果页面存在script、style等隐藏标签内的文本,可使用此方案仅统计用户可见的文本:
function findOccurrences(char) { let totalCount = 0; const escapedChar = char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // 递归遍历所有节点,仅处理可见文本节点 function traverseNode(node) { if (node.nodeType === Node.TEXT_NODE) { const parentTag = node.parentNode.tagName.toLowerCase(); // 排除脚本、样式等非可见标签的文本 if (!['script', 'style', 'noscript'].includes(parentTag)) { const matches = node.textContent.match(new RegExp(escapedChar, 'g')); if (matches) totalCount += matches.length; } } else if (node.nodeType === Node.ELEMENT_NODE) { // 递归遍历子节点 for (const child of node.childNodes) { traverseNode(child); } } } traverseNode(document.body); return totalCount; }
页面显示代码(与原HTML兼容)
<strong><strong>text here (</strong></strong> <span id="anm_tot" class="wysiwyg-font-size-normal"> </span> <strong>) </strong> <script> var countElement = document.getElementById('anm_tot'); countElement.textContent = findOccurrences('¤'); </script>
内容的提问来源于stack exchange,提问作者Tammy Morrison
相关产品推荐
相关产品推荐

