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

相同JS代码工具在其他站点正常,在one-stop-office-shop.nl报Uncaught ReferenceError

问题排查及解决方案

核心报错原因

Uncaught ReferenceError: tcoberekenen is not defined 本质是JS函数没有挂载到全局作用域,和当前部署站点的资源加载逻辑有关,可按以下顺序排查:

  • 脚本加载顺序问题:当前站点大概率把你提供的JS代码放在了DOM元素的后面,或者脚本被设置为延迟/异步加载。Codepen和测试站点默认会把JS放在<head>标签或者DOM渲染前加载,函数先注册完成再渲染带onclick属性的DOM,所以运行正常。
    解决方法:把<script>标签的所有代码整体移到页面<head>标签内,或者放在对应HTML结构的前面,确保函数先注册完成再渲染带onclick属性的输入框和容器。
  • 站点JS作用域隔离:多数商业建站系统会默认把自定义插入的JS代码包裹在局部作用域中(比如放在自执行函数、DOMContentLoaded回调内),你声明的function tcoberekenen()属于局部函数,而onclick属性绑定的事件只能调用全局window下的函数,因此无法识别函数。
    解决方法:把函数挂载到全局window对象上,替换原函数声明为以下代码,原函数内部逻辑不需要修改:
    window.tcoberekenen = function(){
      const zwart=0.00849;
      const kleur=0.05486;
    
      let aantalzwart=document.rekenen.aantalzwart.value;
      let aantalkleur=document.rekenen.aantalkleur.value;
      let zwarttotaal=aantalzwart*zwart;
      let kleurtotaal=aantalkleur*kleur;
      let totaal=zwarttotaal+kleurtotaal;
      document.rekenen.zwarttotaal.value=zwarttotaal.toFixed(2);
      document.rekenen.kleurtotaal.value=kleurtotaal.toFixed(2);
      document.rekenen.totaal.value=totaal.toFixed(2);
    }
    
    注:以上代码已经移除原函数里重复声明zwarttotaal、kleurtotaal的冗余逻辑,不影响原有功能。
  • 内容安全策略(CSP)限制:部分站点的CSP配置禁止内联onclick事件执行,也会触发同类报错。
    解决方法:移除所有DOM上的onclick="tcoberekenen()"属性,改成事件监听的方式绑定事件,把以下代码加在上面的函数后面即可:
    document.addEventListener('DOMContentLoaded', function(){
      const rekentool = document.getElementById('rekentool');
      const aantalzwartInput = document.querySelector('input[name="aantalzwart"]');
      const aantalkleurInput = document.querySelector('input[name="aantalkleur"]');
      [rekentool, aantalzwartInput, aantalkleurInput].forEach(el => {
        el.addEventListener('click', tcoberekenen);
        el.addEventListener('input', tcoberekenen);
      })
    })
    
    额外新增的input事件可以实现用户输入数值时自动计算,提升使用体验。

验证步骤

调整完成后打开浏览器控制台,输入window.tcoberekenen,如果输出对应函数内容就说明已经成功挂载到全局,功能可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:45:08