【发布时间】: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