首页 文章

更改DIV颜色复选框onclick IN LOOP

提问于
浏览
0

我现在已经搜索了几个小时试图实现脚本来改变div背景 . 我发现这个解决方案在不在循环中时有效:

Javascript: onClick checkbox change div color

这里的挑战是复选框位于具有唯一id值的foreach循环中 .

这是我的代码:

<script language="JavaScript" type="text/JavaScript">
function myFunction(x, _this) {
  if (_this.checked) {
    x.style.backgroundColor = '#0000FF';
  } else  {
    x.style.backgroundColor = '#FF0000';
  }
}
</script>
<style type="text/css">
#result {
  background-color: #FF0000;
  padding: 7px;
  margin: 7px;
}
</style>
</head>

<body>
 <?php
    $SL = 0;
    foreach($results_resultat as $key => $row_resultat) { ?>
<div id="result">
  <input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(result, this)">
</div>
<?php } ?>

使用此代码,它将显示从表格中选择的所有行,但单击复选框时不会更改div颜色 .

非常感谢帮助 . :-)

2 回答

  • 1

    您正在使用相同的ID result 来包装所有复选框元素 . id 应该是唯一的,而是使用 class="result" 来包装你的复选框元素 . 另外,除了 this 之外,您不必向 myFunction 函数发送任何内容 . 因此,请按以下方式更改代码,

    CSS

    .result {
        background-color: #FF0000;
        padding: 7px;
        margin: 7px;
    }
    

    PHP

    <?php
        $SL = 0;
        foreach($results_resultat as $key => $row_resultat) { ?>
            <div class="result">
                <input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(this)">
            </div>
            <?php 
        } 
    ?>
    

    JavaScript

    function myFunction(_this) {
        if (_this.checked) {
            _this.parentElement.style.backgroundColor = '#0000FF';
        } else  {
            _this.parentElement.style.backgroundColor = '#FF0000';
        }
    }
    
  • 0

    您的代码的问题是该行: onChange="myFunction(result, this)" . 在该行没有定义结果,通常传递带有选择器的字符串或带有id的字符串 . 这样的东西 onChange="myFunction('result', this)"

    然后在你 JS 函数中使用 document.getElementById 来获取对DOM元素的引用 .

    <script language="JavaScript" type="text/JavaScript">
    function myFunction(id, _this) {
      if (_this.checked) {
        document.getElementById(id).style.backgroundColor = '#0000FF';
      } else  {
        document.getElementById(id).style.backgroundColor = '#FF0000';
      }
    }
    </script>
    

相关问题