繁体   English   中英

为什么在调用document.getElementsByClassName时我的函数返回未定义?

[英]Why does my function return undefined when calling document.getElementsByClassName?

我正在尝试使用css / JavaScript创建一个简单的开关。 在下面,您可以看到即时通讯正在调用

document.getElementsByClassName('onOffSwitch').style.animation = 'off';

jsBin

js要了解我所说的名为“ onOffSwitch”的div,还需要什么其他代码? 想知道为什么当前的代码集不起作用以及如何解决它。

getElementsByClassName()返回集合。 如下指定index

document.getElementsByClassName('onOffSwitch')[0].style.animation = 'off';

因为.getElementsByClassName()返回元素的活动节点列表 (集合),并且您试图设置集合的样式,而不是集合中的一个元素的样式:

// Change the animation style of the first element with the class "onOffSwitch"
document.getElementsByClassName('onOffSwitch')[0].style.animation = 'off';

另外,由于.getElementsByClassName()返回一个“活动”节点列表(每次使用分配给该列表的变量时都会更新的列表),因此,它实际上会降低性能。 在大多数情况下,静态节点列表会更好,您可以使用以下方法实现:

document.querySelectorAll(".onOffSwitch");

但是,同样的规则适用。 那是整个收藏。 您需要访问集合中的各个元素以使用其属性。

现在,查看您的代码,您实际上根本不需要集合。 您只有一个div class="onOffSwitch" ,因此您可以使用以下命令获得一个元素:

document.querySelector("div.onOffSwitch");

然后,您可以直接使用它。

 let state = { switchG: 'On', bits: [0,1,0,1] }; // Get reference to the div var divSwitch = document.querySelector('div.onOffSwitch'); // Set up event handler divSwitch.addEventListener("click", flipSwitch); function flipSwitch() { if (state.switchG == 'On'){ state.switchG = 'Off'; console.log(state.switchG); divSwitch.style.animation = 'off 1s 1'; } else { state.switchG = 'On'; console.log(state.switchG); divSwitch.style.animation = 'on 1s 1'; } } 
 .onOffSwitch{ background-color: #4dc71f; border-radius: 5px; position: absolute; left: 40%; height: 20px; width: 55px; overflow: hidden; text-align: center; cursor:pointer; } @keyframes off { 0%{ background-color: green; } 100%{ background-color: red; } } @keyframes on { 0%{ background-color: red; } 100%{ background-color: green; } } 
 <div class = 'onOffSwitch'>On</div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM