如何将对象与DOM元素关联 [英] How to Associate an Object with a DOM Element
问题描述
我的JS设置中有一个主对象,即:
I have a master object in my JS setup, i.e.:
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
}
]
}
现在我循环上车并将它们放在一张桌子上。在表格中,我还有一个按钮,可让我将车辆切换为使用中和未使用中。
Now I loop over my cars and put them in a table. In the table I also have a button that lets me toggle the car as "in use" and "not in use".
如何将每行的DOM元素与其对应的汽车相关联,这样如果我切换inuse标志,我可以更新主对象?
How can I associate the DOM Element of every row with its corresponding car, so that if I toggle the "inuse" flag, I can update the master object?
推荐答案
我建议考虑 addEventListener
,以及符合你对象的构造函数到 eventListener
界面。
I'd suggest considering addEventListener
, and a constructor that conforms your objects to the eventListener
interface.
这样你就可以在对象,元素和它之间建立良好的关联处理程序。
That way you can have a nice association between your object, your element, and its handlers.
为此,请创建一个特定于您的数据的构造函数。
To do this, make a constructor that's specific to your data.
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()
处理程序。
Then implement your .click()
handler on the prototype.
Car.prototype.click = function(e) {
// do something with this.element...
this.element.style.color = "#F00";
// ...and the other properties
this.inuse = !this.inuse
}
那么你可以循环遍历数组,并为每个项目创建一个新的 Car
对象,它将会创建新元素并添加监听器。
So then you can just loop over the Array, and make a new Car
object for each item, and it'll create the new element and add the listener(s).
myGarage.cars.forEach(function(obj) {
new Car(obj)
})
这篇关于如何将对象与DOM元素关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!