繁体   English   中英

功能不符合预期。 为什么?

[英]Function is not behaving as intended. Why?

抱歉,标题不够准确。

https://jsfiddle.net/ptxsha6m/1/

<script>
var theID = document.getElementById('result1');

function change(){
    var checkboxes = document.getElementsByClassName('checkbox');
    var chekboxInputs = Array.from(checkboxes).map(a => a.querySelector('input'));
    var allAreUnselected = chekboxInputs.every(function(elem){
       return !elem.checked;
    });
    if(allAreUnselected){
       chekboxInputs.forEach(function(input){
          Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(theID){
              theID.style.background = 'blue';
          });
       });
    }
    else {
      chekboxInputs.forEach(function(input){
          Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(theID){
            theID.style.background = input.checked ? 'red' : 'gray';
          });
       });
    }
}
change();
</script>

基本上,正如我所写的,一旦选中一个复选框,它应该将背景黄色的div#id更改为红色。 但是由于某种原因,它坚持只针对带有类的div。

我知道逻辑上肯定有问题,我可以说几件事,但我不明白。 例如,在“ if(allAreUnselected)”处,是否不应该将黄色框的背景设置为蓝色? 既然没有选择?

我想要实现的是能够在函数内部操纵div#。 有什么帮助吗?

谢谢

在脚本的早期,您在一个名为theID的变量中捕获了您正在谈论的DOM元素:

var theID = document.getElementById('result1');

稍后,在更改元素颜色的位置,您在forEach中使用了一个匿名函数,该函数具有一个称为theID的参数:

(/* lots of code */).forEach(function(theID){
    theID.style.background = 'blue'
});

该参数名称掩盖了先前定义的变量,因此当您在该函数内使用theID ,它引用的是每个forEach元素而不是#result1元素-并且您最终决不会尝试更改#result1的颜色。

如果要更改该容器的颜色,请使用其他参数名称,因此该变量不会被其掩盖:

(/* lots of code */).forEach(function(foo){
    foo.style.background = 'blue'
    theID.style.background = // your logic here for deciding what color #result1 should be
});

...或者在匿名函数之外执行:

if(allAreUnselected){
   theID.style.background = 'blue';
   chekboxInputs.forEach(function(input){
     (/* lots of code */).forEach(function(theID){   // (I'd still change that parameter name, though, because masked variables are confusing)

在第41行中,您认为theID变量是错误的。 在这种情况下,变量theID将被forEach函数作为回调函数(theID){..}的参数传递的变量遮盖。

forEach将数组中的每个项目作为参数传递给您在每次迭代中声明的函数。 尝试更改此变量的名称,例如。 ...forEach(function(chekboxInput) { chekboxInput.style.background = 'blue';}没有任何变化。

从这里开始, theID不再是id = result1的div,而是您正在迭代的chekboxInputs中的元素之一。

另请参见丹尼尔·贝克(Daniel Beck)的回答。

暂无
暂无

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

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