javascript对象:变量全局无法读取不同的函数

时间:2016-10-14 11:29:09

标签: javascript variables object styles undefined

我有这个脚本



var b = {
  c: {
    a: document.querySelector(".a"),
    init: function() {
      this.a.style.backgroundColor = "red";
      this.a.addEventListener("click", b.c.change);
    },
    change: function() {
      this.a.style.width = "100px";
    }
  }
}
b.c.init();

.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}

<div class="a"></div>
&#13;
&#13;
&#13;

为什么这个风格&#34;取消定义&#34; ???

3 个答案:

答案 0 :(得分:1)

在更改事件处理程序中,(\G(?!\A))引用dom元素。因此,只需将this更改为this.a.style....

&#13;
&#13;
this.style....
&#13;
var b = {
  c: {
    a: document.querySelector(".a"),
    init: function(){
      this.a.style.backgroundColor="red";
      this.a.addEventListener("click", b.c.change);
    },
    change: function(){
      this.style.width="100px";
    }
  }
}
b.c.init();
&#13;
.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

首先,在更改事件中,this指向DOM元素而不是对象。因此,您可以使用this直接更新样式。

其次,在a内,this将指向c,因此您可以直接执行b.c.change

而不是this.change

var b = {
  c: {
    a: document.querySelectorAll(".a"),
    init: function() {
      for (var i = 0; i < this.a.length; i++) {
        this.a[i].style.backgroundColor = "red";
        this.a[i].addEventListener("click", this.change);
      }
    },
    change: function() {
      console.log(this.innerHTML)
      this.style.width = "100px";
    }
  }
}
b.c.init();
.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
  margin: 5px;
  padding: 5px;
}
<div class="a">1</div>
<div class="a">2</div>
<div class="a">3</div>
<div class="a">4</div>
<div class="a">5</div>

答案 2 :(得分:-4)

尝试一次这将有效..

&#13;
&#13;
var b = {
  c: {
    a: document.getElementById("a"),
    init: function(){
      this.a.style.backgroundColor="red";
      this.a.addEventListener("click", b.c.change);
    },
    change: function(){
      this.style.width="100px";
    }
  }
}
b.c.init();
&#13;
#a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
&#13;
<div id="a"></div>
&#13;
&#13;
&#13;