You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:16:05