javascript – 如何将对象与DOM元素相关联

我的JS设置中有一个主对象,即:
var myGarage = {
    cars: [
        {
            make: "Ford",model: "Escape",color: "Green",inuse: false
        },{
            make: "Dodge",model: "Viper"
            color: "Red",inuse: true
        },{
            make: "Toyota",model: "Camry"
            color: "Blue",inuse: false
        }
    ]
}

现在我绕过我的车,把它们放在桌子上.在桌子上,我还有一个按钮可以让我将汽车切换为“使用中”和“不使用”.

如何将每行的DOM元素与其对应的车辆相关联,以便如果我切换“inuse”标志,我可以更新主对象?

解决方法

我建议考虑addEventListener和一个构造函数,将对象与eventListener接口相符合.

这样,您可以在对象,元素和其处理程序之间建立良好的关联.

为此,请创建一个特定于您的数据的构造函数.

function Car(props) {
    this.make = props.make;
    this.model = props.model;
   // and so on...

    this.element = document.createElement("div"); // or whatever

    document.body.appendChild(this.element);      // or whatever

    this.element.addEventListener("click",this,false);
}

然后实现界面:

Car.prototype.handleEvent = function(e) {
    switch (e.type) {
        case "click": this.click(e);
        // add other event types if needed
    }
}

然后在原型上实现.click()处理程序.

Car.prototype.click = function(e) {
    // do something with this.element...
    this.element.style.color = "#F00";

    // ...and the other properties
    this.inuse = !this.inuse
}

因此,您可以循环使用Array,并为每个项目创建一个新的Car对象,并创建新元素并添加侦听器.

myGarage.cars.forEach(function(obj) {
    new Car(obj)
})

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...