繁体   English   中英

JavaScript - 勾选复选框时文本不会改变颜色

[英]JavaScript - Text won't change color when checkbox is ticked

这是我的脚本:

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

这是我试图将其链接到的html/php

<p style="color: #FF0000; font-weight: bold;" id="termsText">
    I agree to the terms and conditions
    <input type="checkbox" name="termsChkbx">
</p>

当复选框被勾选时,我需要将文本的颜色更改为黑色,而在未勾选时更改为红色。 我不确定我哪里出错了,任何帮助表示赞赏。

var chk = document.querySelector('input[name="termsChkbx"]');

以下代码片段对我有用。 您没有传递要选择的正确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>

您可以改用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>

使用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";
  }
}

考虑简化您的代码:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM