[英]JavaScript - Text won't change color when checkbox is ticked
This is my script:这是我的脚本:
<script type="text/javascript">
"use strict";
var chk = document.querySelector('termsChkbx');
document.getElementsByName("termsChkbx").onclick = function() {textCol()};
function textCol()
{
if(chk.checked){
document.getElementById("termsText").style.color = "black";
}
}
</script>
And this is the html/php that I'm trying to link it to.这是我试图将其链接到的html/php 。
<p style="color: #FF0000; font-weight: bold;" id="termsText">
I agree to the terms and conditions
<input type="checkbox" name="termsChkbx">
</p>
I need the color of the text to change to black when the checkbox is ticked and back to red when it isn't.当复选框被勾选时,我需要将文本的颜色更改为黑色,而在未勾选时更改为红色。 I'm not sure where I am going wrong, any help is appreciated.
我不确定我哪里出错了,任何帮助表示赞赏。
var chk = document.querySelector('input[name="termsChkbx"]');
The following code snippet works for me.以下代码片段对我有用。 You were not passing the correct
id
to be selected.您没有传递要选择的正确
id
。
"use strict"; var chk = document.querySelector('#termsChkbx'); document.getElementById("termsChkbx").onclick = function() {textCol()}; function textCol() { if(chk.checked){ document.getElementById("termsText").style.color = "black"; }else document.getElementById("termsText").style.color = "red"; }
<p style="color: #FF0000; font-weight: bold;" id="termsText">I agree to the terms and conditions <input type="checkbox" name="termsChkbx" id="termsChkbx"></p>
You can use document.getElementsByName
instead.您可以改用
document.getElementsByName
。
"use strict"; var chk = document.getElementsByName('termsChkbx')[0]; document.getElementsByName('termsChkbx')[0].onclick = function() { textCol() }; function textCol() { if (chk.checked) { document.getElementById("termsText").style.color = "black"; } else { document.getElementById("termsText").style.color = "red"; } }
<p style="color: #FF0000; font-weight: bold;" id="termsText">I agree to the terms and conditions <input type="checkbox" name="termsChkbx"></p>
Use querySelector("#termsText input")
to be sure that the target is the input.使用
querySelector("#termsText input")
确保目标是输入。
"use strict";
var chk = document.querySelector("#termsText input");
chk.onclick = function() {
textCol()
};
function textCol() {
var paragraph = document.getElementById("termsText");
if (chk.checked) {
paragraph.style.color = "black";
} else {
paragraph.style.color = "red";
}
}
Consider simplifying your code:考虑简化您的代码:
document.querySelector('.trmsChkbx').onclick = function() { document.querySelector(".trmsTxt").style.color = this.checked ? "#000" : "#f00"; }
.trmsTxt{ color: #f00; font-weight: 700; }
<label class="trmsTxt" id="trmsTxt"> I agree to the terms and conditions <input type="checkbox" name="trmsChkbx" class="trmsChkbx"> </label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.