ReferenceError: count_1 is not defined in a Joomla module

ReferenceError: count_1 is not defined in a Joomla module

这是我的脚本:

<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
    var INTERVAL_1 = 3; // in seconds
    var INCREMENT_1 = 1; // increase per tick
    var START_VALUE_1 = 0; // initial value when it's the start date
    var count_1 = 0;

    var msInterval_1 = INTERVAL_1 * 1000;
    var now_1 = new Date();
    count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
    document.getElementById('counter_1').innerHTML = count_1;
    setInterval("count_1 += INCREMENT_1; document.getElementById('counter_1').innerHTML = count_1;", msInterval_1);
  });
</script>

我已将它放入 Joomla 模块中。 Firebug 说:"ReferenceError: count_1 is not defined"

为什么?我该如何解决?

您应该将函数而不是字符串传递给 setInterval 调用。当你传递一个字符串时,它是在全局范围内执行的,而count_1变量只存在于传递给addEventListener.

的回调函数的范围内
<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
    var INTERVAL_1 = 3; // in seconds
    var INCREMENT_1 = 1; // increase per tick
    var START_VALUE_1 = 0; // initial value when it's the start date
    var count_1 = 0;

    var msInterval_1 = INTERVAL_1 * 1000;
    var now_1 = new Date();
    count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
    document.getElementById('counter_1').innerHTML = count_1;
    setInterval(function() {
      count_1 += INCREMENT_1;
      document.getElementById('counter_1').innerHTML = count_1;
    }, msInterval_1);
  });
</script>

当您将字符串作为第一个参数传递给计时器函数时,它们实际上会创建一个脚本对象并将其作为源:

[Otherwise]

Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, report the exception.

Let script source be the first method argument.

Let settings object be method context's environment settings object.

Let script be the result of creating a classic script using script source and settings object.

Run the classic script script.

https://html.spec.whatwg.org/multipage/webappapis.html#dom-setinterval

因此,它并不完全像 eval 您实际访问函数范围的地方。脚本对象应该可以访问全局范围。它失败的原因是因为它通过找不到 count_1 += INCREMENT 在全局范围内寻找 count_1,因此 returns ReferenceError.

避免此类错误的最佳方法是不使用字符串作为定时器函数的参数。