JavaScript从自定义对象访问元素

JavaScript access elements from custom object

本文关键字:访问 元素 对象 自定义 JavaScript      更新时间:2023-09-26

这一定是一个非常愚蠢的问题,但我就是不能让它工作。

我正在为iOS创建自己的UIKit。(网站工具包,将允许类似iphone的界面)。

但是,我正在尝试创建一个JavaScript库,它可以用来改变文档的几个元素。例如,在文档加载时设置自定义背景颜色。

我正试图用面向对象的JavaScript做到这一点。这样的:

var UI = new Interface();
UI.setBackground("#000");

我怎样才能做到这一点?(所以自定义的"UI"对象,和(一个例子)如何改变文档的背景色,从内部对象)

你可以在JS对象中保存对DOM的引用,并根据需要重写它。

function Interface() {
    this.setBackground = function (color) {
        this.pointTo.style.background = color;
    };
    this.pointTo = document.body;
}

你可以初始化它:

var UI = new Interface();
UI.pointTo = document.getElementById('some_id');
UI.setBackground("#000");
// Set another style, on a different element
UI.pointTo = document.getElementById('some_other_id');
UI.setBackground("#FFF");

这是一个简单的实现,需要更聪明,但它应该完成工作。

编辑:在原始发布中犯了错误,并修正了错误代码。也做了一个例子:http://jsfiddle.net/HpW3E/

与silverstrike的代码类似,但是您可以在接口构造函数中传递目标对象,以避免将来出现问题。

function Interface(target) {
    target = target || document.body;
    this.setBackground = function (color) {
        target.style.background = color || 'white';
    };
}

现在你可以这样做:

var UI = new Interface(document.body);
UI.setBackground("#000");

,甚至在某些情况下,您正在应用global scope !ONLY!:

var UI = new Interface(this.body);
UI.setBackground("#000");

也可以这样工作:

var UI = new Interface();
UI.setBackground("#000");

这是一个非常简单的方法

// define the object
var Interface = function () {
    var interface = document.getElementById("interface"); // just an example
    // your new methods
    this.setBackground = function (color) {
        interface.style.backgroundColor = color;
    }
    // rest of your code
}

现在你可以利用它了

var UI = new Interface();
UI.setBackground("#000");