我的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)
})