【问题标题】:Javascript Internal class not found by document.getElementByClassNamedocument.getElementsByClassName 找不到 Javascript 内部类
【发布时间】:2018-02-10 18:01:40
【问题描述】:

我正在制作一个物理引擎,它利用 JavaScript 创建具有物理属性的盒子,这些盒子以窗口大小的比例应用于它们。但是,函数document.getElementByClassName("box") 找不到包含这些盒子的所有物理属性的名为box 的类。

我正在尝试分配一个变量boxelem 来包含每个单独框的位置属性,以便将来可以将鼠标操作集成到我的程序中。我试过通过代码做到这一点:
var boxelem = document.getElementsByClassName("box"); 然后将鼠标悬停事件监听器添加到 boxelem。

必要代码:

var canvas;
var ctx;
var box = [];
var boxelem;

//Startup Code
window.onload = function(e) {
    canvas = document.getElementById("c");
    ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    box = [new box(10, 20, "cyan"), new box(299, 40, "red"), new box(90, 50,
      "black"), new box(29, 20, "turquoise")];
    boxelem = document.getElementsByClassName("box");
    noscroll();
    update();
  }

  //Physic Clock (For real-time physics)
var clock = {
    lasttick: 0,
    tick: function() {
      var td = performance.now() - this.lasttick;
      this.lasttick = performance.now();
      return td / 1000;
    },
    reset: function() {

    }
  }

  //Box objects be created here (Box Class)
var box = function(x, y, color) {
  var _this = this;
  //First Spawn Physics and Settings
  _this.x = Math.random() * (canvas.width - 50);
  _this.y = Math.random() * (canvas.height - 50);
  _this.vx = 0;
  _this.vy = Math.random() * 150;
  _this.ax = 0;
  _this.ay = 440;
  _this.color = color;

  _this.draw = function() {
      ctx.fillStyle = _this.color;
      ctx.fillRect(_this.x, _this.y, 50, 50);
    }

    //Normal Physics
  _this.update = function(t, mX, mY) {
    if (mX != 0) {
      _this.x += _this.vx * t;
      _this.vx += mX * t;
    } else {
      _this.x += _this.vx * t;
      _this.vx += _this.ax * t;
    }
    _this.y += _this.vy * t;
    _this.vy += _this.ay * t;

    //Boundary Creation
    if ((_this.y + 55) > canvas.height) {
      _this.vy -= _this.ay * t;
      _this.vy = 0;

    }
    if ((_this.x + 55) > canvas.width) {
      _this.vx -= _this.ax * t;
      _this.vx = 0;
    }
    if ((_this.y) < 0) {
      _this.vy -= _this.ay * t;
      _this.vy = 0;
      _this.y = (canvas.height + 20);
    }
    if ((_this.x) < 0) {
      _this.vx -= _this.ax * t;
      _this.vx = 0;
    }
  }
}

//Get mouse position if over a box
var pageX = 0;
var pageY = 0;
for (var z = 0; z < box.length; z++) {
  boxelem.addEventListener("mouse", mPos, false);
}

底部的事件监听器给出错误,因为boxelem 未定义,因为getElementsByClassName 找不到元素。 HTML 代码:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
     <script type=text/javascript src="Physics.js"></script>
     <meta charset="utf-8" />
     <title>Physics Engine of Boxes</title>
 </head>
 <body>
     <canvas id="c"></canvas>
</body>
</html>

我查看了 (Unobtrusive Javascript-Basic Implementation: How do I bind all elements of a particular class to a function in Javascript?) 和 (Change an element's class with JavaScript),但不确定如何将其应用于我的问题。

【问题讨论】:

  • 我没有看到类 box 的元素。所以document.getElementsByClassName("box")方法总是返回一个空数组。
  • document.getElementByClassName() 是否可以引用在 JS 而不是 HTML 中实例化的类? @D.西蒙
  • document.getElementsByClassName("box") 查找具有给定类的 HTML 元素。找不到 JavaScript classes,因为 JS 没有真正的类。
  • 我现在明白了,虽然我如何在不创建 HTML 类的情况下引用 box 类的元素?

标签: javascript getelementsbyclassname


【解决方案1】:

你的循环体没有访问索引。此外,您使用的 .length 来自 box 函数,而不是 boxelem 集合。

这个:

for (var z = 0; z < box.length; z++) 
{
  boxelem.addEventListener("mouse", mPos, false);
}

应该是这样的:

for (var z = 0; z < boxelem.length; z++) 
{
  boxelem[z].addEventListener("mouse", mPos, false);
}

正如 D Simon 在下面指出的,boxelemundefined,因为在 DOM 加载之前您不会填充该变量。在尝试使用该变量之前,您应该确保获取这些项目。


如果您将所有代码移至window.onload,它应该可以工作。请注意,window.onload 在加载所有资源之前不会运行。您可能希望使用更快触发的不同事件,但这是另一个主题。

//Startup Code
window.onload = function(e) {
    var canvas = document.getElementById("c");
    var ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var box = [new box(10, 20, "cyan"), new box(299, 40, "red"), new box(90, 50,
      "black"), new box(29, 20, "turquoise")];
    var boxelem = document.getElementsByClassName("box");
    noscroll();
    update();

    //Physic Clock (For real-time physics)
    var clock = {
        lasttick: 0,
        tick: function() {
          var td = performance.now() - this.lasttick;
          this.lasttick = performance.now();
          return td / 1000;
        },
        reset: function() {

        }
      }

    //Box objects be created here (Box Class)
    var box = function(x, y, color) {
      // ...implementation...
    }

    //Get mouse position if over a box
    var pageX = 0;
    var pageY = 0;
    for (var z = 0; z < boxelem.length; z++) {
      boxelem[z].addEventListener("mouse", mPos, false);
    }
}

【讨论】:

  • 你是对的。但实际问题是 boxelem 未定义。
  • @D.Simon:谢谢,我也为此添加了注释。
  • 这意味着将 fetch 语句移到 window.onload 函数之前,对吗?
  • @KyleMyott:如果你这样做,并且脚本位于页面顶部,那么它将返回一个空集合。您可以移动 window.onload 中的所有代码,或在页面加载时运行的另一个事件
猜你喜欢
  • 2013-11-07
  • 2012-01-07
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多