Chrome扩展字符计数器问题:仍统计style与script标签内容
解决办法
原代码仅过滤了body的直接子节点中的<script>和<style>元素,但对于嵌套在其他元素内的这类标签,或是通过text()递归获取文本时,仍会包含标签内的内容。可以用以下两种方式解决:
方法一:克隆DOM并移除目标标签
这种方式简单高效,通过克隆body内容并移除所有<script>和<style>标签,再统计剩余文本的字符数:
$(document).ready(function() { // 克隆body内容,避免修改原页面DOM结构 var bodyClone = $("body").clone(); // 移除所有script和style标签 bodyClone.find("script, style").remove(); // 去除所有空格后统计字符数 var length = bodyClone.text().replace(/ +/g, "").length; console.log(length); });
方法二:递归遍历节点过滤
如果需要更精细地控制节点处理,可以递归遍历所有节点,跳过<script>、<style>元素及其子节点:
$(document).ready(function() { function calculateTextLength(node) { let totalLength = 0; $(node).contents().each(function() { // 处理元素节点:非script/style则递归遍历其子节点 if (this.nodeType === 1) { if (this.localName !== "script" && this.localName !== "style") { totalLength += calculateTextLength(this); } } // 处理文本节点:去除空格后累加长度 else if (this.nodeType === 3) { totalLength += this.textContent.replace(/ +/g, "").length; } }); return totalLength; } var length = calculateTextLength($("body")); console.log(length); });
内容的提问来源于stack exchange,提问作者Luna McGrove
相关产品推荐
相关产品推荐

