我现在已经搜索了几个小时试图实现脚本来改变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 回答
您正在使用相同的ID
result
来包装所有复选框元素 .id
应该是唯一的,而是使用class="result"
来包装你的复选框元素 . 另外,除了this
之外,您不必向myFunction
函数发送任何内容 . 因此,请按以下方式更改代码,CSS
PHP
JavaScript
您的代码的问题是该行:
onChange="myFunction(result, this)"
. 在该行没有定义结果,通常传递带有选择器的字符串或带有id的字符串 . 这样的东西onChange="myFunction('result', this)"
然后在你
JS
函数中使用document.getElementById
来获取对DOM元素的引用 .