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

如何将document.write转换为innerHTML?改写文章总数统计脚本

改写为innerHTML的实现方案

你只需要修改回调函数里的输出逻辑,不再使用document.write,而是直接定位到目标<span class='count'>元素,通过innerHTML插入统计数值。这样更符合现代DOM操作规范,也能避免document.write可能带来的页面渲染问题。

修改后的完整代码如下:

<script>
function mbhTotalCount(json) {
  var totalCount = parseInt(json.feed.openSearch$totalResults.$t, 10);
  // 定位到承载统计数的span元素
  var countElement = document.querySelector('.count');
  // 确保元素存在再设置内容,避免报错
  if (countElement) {
    countElement.innerHTML = totalCount;
  }
}
</script>
<span class='count'>
  <script src="/feeds/posts/default?alt=json-in-script&callback=mbhTotalCount"></script>
</span>

核心改动说明:

  • 替换document.write(totalCount)为DOM元素定位+内容赋值的逻辑
  • 增加元素存在性判断,避免因DOM加载顺序问题导致的控制台报错
  • 通过innerHTML将统计数值直接插入目标容器,实现和原代码一致的展示效果

内容的提问来源于stack exchange,提问作者Sulav Shrestha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:37:09