简体   繁体   English

JavaScript解析错误-Google跟踪代码管理器

[英]Javascript parse error - Google Tag Manager

I have tried to create a custom JavaScript GTM variable after reading a tutorial. 阅读指南后,我尝试创建一个自定义JavaScript GTM变量。

But I just get the message that I have a parse error. 但是我只收到一条消息,提示我存在解析错误。

Error at line 43, character 5: Parse error. 第43行的错误,字符5:解析错误。 ')' expected ')'预期

Not sure what's wrong here. 不知道这里出了什么问题。 Any ideas? 有任何想法吗? thanks. 谢谢。

function countdown(endDate) {
  var days, hours, minutes, seconds;

  endDate = new Date(endDate).getTime();

  if (isNaN(endDate)) {
    return;
  }

  setInterval(calculate, 1000);

  function calculate() {
    var startDate = new Date();
    startDate = startDate.getTime();

    var timeRemaining = parseInt((endDate - startDate) / 1000);

    if (timeRemaining >= 0) {
      days = parseInt(timeRemaining / 86400);
      timeRemaining = (timeRemaining % 86400);

      hours = parseInt(timeRemaining / 3600);
      timeRemaining = (timeRemaining % 3600);

      minutes = parseInt(timeRemaining / 60);
      timeRemaining = (timeRemaining % 60);

      seconds = parseInt(timeRemaining);

      document.getElementById("days").innerHTML = parseInt(days, 10);
      document.getElementById("hours").innerHTML = ("0" + hours).slice(-2);
      document.getElementById("minutes").innerHTML = ("0" + minutes).slice(-2);
      document.getElementById("seconds").innerHTML = ("0" + seconds).slice(-2);
    } else {
      return;
    }
  }
}

(function () { 
  countdown('09/06/2019 12:00:00 AM'); 
}());

The syntax of a Custom Javascript variable in GTM is the following: GTM中的自定义Javascript变量的语法如下:

 function() {
   //your code
   return //your result;
 }

This is the reason, why you get an error message, when you try to save your code. 这就是为什么当您尝试保存代码时收到错误消息的原因。

So you need to include only the core functionality, you want to achieve here. 因此,您只需要包括此处要实现的核心功能即可。 However, this type of variable should be used primarily to calculate and return a value, and not to manipulate the DOM. 但是,这种类型的变量应主要用于计算和返回值,而不是操作DOM。

What you need, is a Custom HTML tag, where the script should be included within a script tag: 您需要的是自定义HTML标签,该脚本应包含在script标签中:

<script>
function countdown(endDate) {
  //your countdown function
}

(function () { 
  countdown('09/06/2019 12:00:00 AM'); 
}());
</script>

You will also need a trigger, which launches this tag upon page load. 您还将需要一个触发器,该触发器将在页面加载时启动此标签。 Possibly, only after DOM or on Window Loaded, so that all elements are available, when your script runs. 可能仅在DOM或窗口加载后才执行,以便在脚本运行时所有元素都可用。

Also please note, that countdown will be created in the global namespace, so you need to take care not to overwrite an other countdown function, or have it overwritten. 还请注意, countdown将在全局名称空间中创建,因此您需要注意不要覆盖其他倒计时功能,或者将其覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM