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

前端之家收集整理的这篇文章主要介绍了javascript – 如何将对象与DOM元素相关联前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的JS设置中有一个主对象,即:
  1. var myGarage = {
  2. cars: [
  3. {
  4. make: "Ford",model: "Escape",color: "Green",inuse: false
  5. },{
  6. make: "Dodge",model: "Viper"
  7. color: "Red",inuse: true
  8. },{
  9. make: "Toyota",model: "Camry"
  10. color: "Blue",inuse: false
  11. }
  12. ]
  13. }

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

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

解决方法

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

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

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

  1. function Car(props) {
  2. this.make = props.make;
  3. this.model = props.model;
  4. // and so on...
  5.  
  6. this.element = document.createElement("div"); // or whatever
  7.  
  8. document.body.appendChild(this.element); // or whatever
  9.  
  10. this.element.addEventListener("click",this,false);
  11. }

然后实现界面:

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

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

  1. Car.prototype.click = function(e) {
  2. // do something with this.element...
  3. this.element.style.color = "#F00";
  4.  
  5. // ...and the other properties
  6. this.inuse = !this.inuse
  7. }

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

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

猜你在找的JavaScript相关文章