创建一个新的用户界面元素对象的Javascript原型

javascript prototype creating a new user interface element object

本文关键字:用户界面 元素 Javascript 原型 对象 一个 创建      更新时间:2023-09-26

我想创建一个javascript对象,可以重用为web应用程序制作复杂的用户界面。我通过使用原型创建了一个javascript对象,上面的例子很好。

var MainWindow = function(width, height){
    this.width = width;
    this.height = height;
    this.html = '';
MainWindow.prototype = {
    toString: function(){
        this.html += '<div id="main_div" style="width:' + this.width + 'px; height:' + this.height + 'px; background-color:#CCC;"></div>';
        return this.html;
    }
}
var newWindow = new MainWindow(400,400);
document.write(newWindow);

现在初始化并创建一个新对象,这很好。但它不能按我想要的方式使用


现在我已经为此创建了另一个示例:-

var Button(text){
    this.text = text;
    this.element = '';
}
Button.prototype = {
    this.element = document.createElement("button");
    this.element.innerHTML = this.text;
    return this.element;
}

var x = document.getElementById("main_div");
element = new Button("ashish");
x.appendChild(element);

第二个例子是错误的,不工作的东西是缺少的,所以我怎么能使它工作。然后创建一个新元素并按我的方式添加

var Button = function(text){
    this.text = text;
    this.element = '';
}
Button.prototype.createButton = function()
{
    this.element = document.createElement("BUTTON");
    this.element.innerHTML = this.text;
    return this.element;
}
var x = document.getElementById("main_div");
element = new Button("ashish"); // your Button should be function object
element=element.createButton(); // you should call the property you added
x.appendChild(element);

JSFIDDLE链接