【问题标题】:Why getElementById returns null when called inside a Class? [duplicate]为什么 getElementById 在类中调用时返回 null? [复制]
【发布时间】:2016-01-25 19:46:14
【问题描述】:

我有一个像下面这样的类,我想传递一个元素以进行进一步的自定义。该类应负责设置框的大小并向其添加元素。我很难为元素应用必要的样式。

class BoxBuilder {
    constructor(element, items) {
        this.items = items;
        this.elm   = document.getElementById(element);
    }
    setSize(h, w) {
        console.log(this.elm); // returns null
        this.elm.style.width = w;
        this.elm.style.height = h;
        return this;
    }
}

使用 jQuery:

class BoxBuilder {
    constructor(element, items) {
        this.items = items;
        this.elm   = $(element);
    }
    setSize(h, w) {
        console.log(this.elm); // returns [context: document, selector: "#box-container"]
        this.elm.style.width = w;
        this.elm.style.height = h;
        return this;
    }
}


// here is what I am trying to achieve
var box = new BoxBuilder('#box-container').setSize(300, 250);

【问题讨论】:

  • 您是否在 DOM 加载后致电 new BoxBuilder(...)
  • 第一个怎么称呼?您是否像使用 jQuery 一样包含“#”?如果你这样做,那就是你的问题......
  • 谢谢...我的问题是在 dom 准备好之前调用它 :) 干杯
  • @RocketHazmat 在类外还是类内更适合处理 dom 就绪事件?
  • 没关系。外面:)

标签: javascript jquery ecmascript-6 javascript-objects


【解决方案1】:

您正在使用不应该使用的 CSS 选择器。 jQuery 采用 CSS 选择器,例如 #box-container,然后去掉 #,因为这表明它是一个 ID。要使用document.getElementById,请避免使用#

所以将你的作业改写为:

var box = new BoxBuilder('box-container').setSize(300, 250);

【讨论】:

    【解决方案2】:

    当您直接使用 JavaScript 时,您会得到 null,因为您没有使用 # 作为 ID 的一部分。这是您正在寻找具有该 ID 的元素的 jQuery 标识符。另一种选择是.,这将是按班级。 (其他 CSS 样式选择器也有效。)

    所以你想在只使用 JavaScript 时发送的是var box = new BoxBuilder('box-container').setSize(300, 250);

    【讨论】:

      【解决方案3】:

      您需要确保在加载 DOM 之后调用document.getElementById。否则,您将找不到任何东西。

      window.addEventListener('load', function(){
          var box = new BoxBuilder('box-container').setSize(300, 250);
      });
      

      【讨论】:

        猜你喜欢
        • 2014-03-28
        • 1970-01-01
        • 2019-11-17
        • 2017-09-27
        • 2012-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        相关资源
        最近更新 更多