【问题标题】:ReferenceError - External Script - Cannot access VariableReferenceError - 外部脚本 - 无法访问变量
【发布时间】:2021-02-24 07:40:40
【问题描述】:

这是我的网站自定义代码:

<script>
function showCookieBanner () {
  //check lang_id
  var policy_id = 0;
  var lang_id = jQuery('html').attr('lang').split('-')[0];
  console.log(lang_id);
  if (lang_id === 'en') {
  policy_id = myID; 
  }
  else if (lang_id === 'de') {
  policy_id = myID; 
  }
  console.log(policy_id)

  //declare Variable for external script (_iub)
  var _iub = _iub || [];
  _iub.csConfiguration = {
  "lang": lang_id,
  "siteId": mySiteID,
  "cookiePolicyId": policy_id,
  };

  //run external script:
  var head= document.getElementsByTagName('head')[0];
  var script= document.createElement('script');
  script.src= '//cdn.iubenda.com/cs/iubenda_cs.js';
  script.type='text/javascript';
  script.charset='UTF-8';
  head.appendChild(script);
}
window.addEventListener('load', showCookieBanner);
</script>

通过这个脚本,我尝试实现 iubenda 的 cookie-banner 解决方案。 首先检查 HMTL 文档的 lang_id。使用 lang_id 确定 policy_id。然后传递给变量_iub。外部脚本需要变量 _iub(参见代码中的注释)。 一切都加载完毕后,整个事情都必须发生,所以我使用“window.addEventListener('load', showCookieBanner)”。

获取 lang_id 和 policy_id 有效(已通过 console.log 检查),但是当我加载页面时收到以下错误消息:

iubenda_cs.js:1 Uncaught ReferenceError: _iub is not defined
    at iubenda_cs.js:1
    at iubenda_cs.js:1
(anonymous) @ iubenda_cs.js:1
(anonymous) @ iubenda_cs.js:1

【问题讨论】:

    标签: javascript uncaught-reference-error


    【解决方案1】:

    尝试将“_iub”变量声明为全局变量,如下所示:

    var _iub = _iub || [];
    
    function showCookieBanner () {
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      相关资源
      最近更新 更多