dpcj40970 2017-09-03 16:40
浏览 75
已采纳

更改DIV颜色复选框onclick IN LOOP

I have searched for several hours now trying to implent scripts to change the div background. I've found this solution which works when it's not in a loop:

Javascript: onClick checkbox change div color

The challenge here is that the checkboxes is in a foreach loop with unique id values.

Here is my code:

<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 } ?>

With this code it will show all the rows which are selected from the tabel but it won't change the div color when clicking the checkbox.

Help is very much appreciated. :-)

  • 写回答

2条回答 默认 最新

  • douying6206 2017-09-03 16:52
    关注

    You're using the same id result to wrap all your checkbox elements. ids should be unique, use class="result" instead to wrap your checkbox elements. Plus, you don't have to send anything except this to myFunction function. So change your code in the following way,

    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';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64