【问题标题】:Main.js file causing the whole page to crashMain.js 文件导致整个页面崩溃
【发布时间】:2021-10-09 22:42:31
【问题描述】:

我正在制作一个多页网站。我只将此预加载器添加到我的索引页。我在索引页面中没有收到错误,但在我的其他页面上出现了很多错误。

我发现的错误: main.js:10 未捕获的类型错误:无法将属性“textContent”设置为 null 这里:

function loader(success) {
  document.body.style.overflowY = 'hidden';

  let time = window.onload;
  let obj = document.querySelector('.preLoader'),
    inner = document.querySelector('.preLoader .count');
  let w = 0,
    t = setInterval(function() {
      w = w + 1;
      inner.textContent = w + '%';
      if (w > 99) {
        obj.classList.add('loaded');
        document.body.style.overflowY = 'auto';
        clearInterval(t);
        w = 0;
        if (success) {
          return success(t);
        }
      }
    }, time);
}
loader();
<!--    PRELOADER    -->
<div class="preLoader t_center g_center fixed" id="preLoader">
  <div class="count">%</div>
</div>

【问题讨论】:

  • 您必须在其他没有预加载器 HTML 的文件中加载 main.js
  • 在运行那段代码之前确保你在索引上。
  • 这是做什么的:let time = window.onload?
  • 或在其余代码周围添加检查:if (inner)
  • 让 time = window.onload 用于预加载器计时。

标签: javascript html opacity


【解决方案1】:

错误消息告诉您,您的 inner 变量已设置为 null,而不是您期望的对 &lt;div&gt; 元素的引用。当document.querySelector('.preLoader .count') 不匹配任何内容时会发生这种情况,在您未包含预加载器的网页上就会出现这种情况。

你可以在使用前检查inner的值不是null来避免这个问题:

if (inner) {
    inner.textContent = w + '%';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多