【问题标题】:javascript object: variable global can not read in different function [closed]javascript对象:变量全局无法在不同的函数中读取[关闭]
【发布时间】:2016-10-14 11:29:09
【问题描述】:

我有这个脚本

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>

为什么 this.a 样式“取消定义”???

【问题讨论】:

  • 我不明白你的问题,对不起

标签: javascript variables object styles undefined


【解决方案1】:

在更改事件处理程序中,this 指的是 dom 元素。所以只需将 this.a.style.... 更改为 this.style....

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();
.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
<div class="a"></div>

【讨论】:

  • 但是如果有多个元素会产生问题,那么使用类选择会产生问题。所以最好使用“id”。
  • @BEJGAMSHIVAPRASAD 你是什么意思?
  • @BEJGAMSHIVAPRASAD 在此特殊设置中,a 将始终仅包含 一个 元素,因为 document.querySelector() 仅返回第一个匹配的元素。
  • 感谢@Pranav C Balan
  • @FerryAlfanso:很高兴为您提供帮助
【解决方案2】:

首先,在更改事件中,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>

【讨论】:

  • 嗨@Rajesh,如果我们在“change”函数中有更多的dom元素怎么样?
  • @FerryAlfanso 你将不得不遍历它们并将处理程序分配给每个元素。请检查更新的答案
  • 嗨@Rajesh,我添加了新的 div.b 并强制扩展更改功能。我对吗?或任何建议?谢谢
  • @FerryAlfan所以你可以更新选择器,它应该可以工作
【解决方案3】:

尝试一次,这会奏效..

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();
#a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
&lt;div id="a"&gt;&lt;/div&gt;

【讨论】:

  • :D thaaaaaaaankkkkkkkkksssss........
  • 这里self 是指向window 的唯一原因是因为您使用id 作为a
  • @Rajesh 这行得通的唯一原因是他创建了一个全局变量调用a
  • @Keith 全局属性a由浏览器创建-> Do DOM tree elements with ids become global variables?
  • ups 抱歉 @BEJGAM SHIVA PRASAD,我太兴奋了,我自己无法正常工作,而且我在更换功能时遇到了更多圆顶问题
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多