[英]How to create a simple DOM element within a constructor and append it to an element on invocation
The comments should be self explanatory. 评论应该是自我解释的。 I simply want to create an element in a constructor and have it appended to the DOM when an object is created with it.
我只想在构造函数中创建一个元素,并在使用它创建对象时将其附加到DOM。
<div id="app">
</div>
Javascript 使用Javascript
function DomItem(name,buttonName,button){
if(typeof(this.button)==='undefined') {
this.button = document.createElement('div');
};
this.buttonName = buttonName;
this.button.className = buttonName;
this.button.id = name +"_ " +buttonName;
var app = document.getElementById("app"); //Works!
console.log(app); // Works!
app.appendChild(button); // Problem ~~~~~~~~~~~~~~~
};
osc = new DomItem('osc','button');
button
within the DomItem
constructor function is undefined
since you are not passing in the third button
parameter. button
的内DomItem
构造函数是undefined
,因为你没有在第三个通过button
参数。 Any named parameter that isn't passed is assigned the value undefined
. 未传递的任何命名参数都将赋值
undefined
。
osc = new DomItem('osc','button'/*, button parameter missing*/);
Use this.button
to refer to the button created within the constructor. 使用
this.button
来引用构造函数中创建的按钮。
app.appendChild(this.button);
Note that this.button
in the below code doesn't refer to the third button
argument but to a property button
of this
, which will always be undefined on calling the constructor. 需要注意的是
this.button
在下面的代码并未提及第三个button
的说法,但到属性button
的this
,它总是会在调用构造函数未定义。
if(typeof this.button ==='undefined') {
this.button = document.createElement('div');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.