Javascript 更改DIV颜色复选框onclick IN循环
我已经搜索了好几个小时了,现在正在尝试执行脚本来更改div背景。我发现这个解决方案在不在循环中时有效: 这里的挑战是,复选框位于具有唯一id值的foreach循环中 这是我的密码:Javascript 更改DIV颜色复选框onclick IN循环,javascript,php,css,checkbox,Javascript,Php,Css,Checkbox,我已经搜索了好几个小时了,现在正在尝试执行脚本来更改div背景。我发现这个解决方案在不在循环中时有效: 这里的挑战是,复选框位于具有唯一id值的foreach循环中 这是我的密码: <script language="JavaScript" type="text/JavaScript"> function myFunction(x, _this) { if (_this.checked) { x.style.backgroundColor = '#0000FF'; }
<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颜色
非常感谢您的帮助- 代码的问题在于:onChange=myFunctionresult这一行。 在该行中,未定义结果,通常使用选择器传递字符串,或使用id传递字符串。 类似这样的onChange=myFunction'result',这是 然后在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>
您正在使用相同的id结果包装所有复选框元素。ID应该是唯一的,使用class=result来包装您的复选框元素。另外,除了这个,你不需要发送任何东西给myFunction。因此,请按以下方式更改代码
CSS
PHP
未定义结果。将结果更改为document.getElementById'result'@Xufox,当浏览器将id为result的元素添加到全局范围作为id时,result将引用id为result的div元素。问题是他们正在创建多个id相同的div,因此只有一个受到影响。它的工作原理如下:您能告诉我如何通过单击DIV层进行更改吗?我已经试过了,但这只会使整个页面变黑我找到了解决办法。。当然,这很简单,只要把它放在周围,识别它就可以了结果是:@Kenneth很高兴我的回答帮助你解决了这个问题:干杯
.result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
<?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
}
?>
function myFunction(_this) {
if (_this.checked) {
_this.parentElement.style.backgroundColor = '#0000FF';
} else {
_this.parentElement.style.backgroundColor = '#FF0000';
}
}