微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

复选框切换内容部分不适用于所有复选框

如何解决复选框切换内容部分不适用于所有复选框

我已经创建了 4 个带有详细信息的复选框切换,但同时只有一个复选框切换在我单击另一个 3 个切换不起作用时起作用,我该如何更改 html 代码的脚本以使所有复选框都起作用。

<!-- Check Box dropdown -->
<script>
function myFunction() {
  // Get the checkBox
  var checkBox = document.getElementById("myCheck");
  // Get the output text
  var text = document.getElementById("text");

  // If the checkBox is checked,display the output text
  if (checkBox.checked == true){
    text.style.display = "block";
  } else {
    text.style.display = "none";
  }
}
</script>
<!-- Check Box dropdown -->
<div class="checkBox">
                     <label><input type="checkBox" id="chkNIRF" onclick="myFunction()"><p class="text-grey">Demo</p></label>
                     <label><input type="checkBox" id="chkNAAC" onclick="myFunction()"><p class="text-grey">Demo</p></label>
                     <label><input type="checkBox" id="chkINI" onclick="myFunction()"><p class="text-grey">Demo</p></label>
                     <label><input type="checkBox" id="chkIoE" onclick="myFunction()"><p class="text-grey">Demo</p></label>
                </div>
                
                   <p id="text" id="text" style="display:none">CheckBox is CHECKED!</p>
                   <p id="text" id="text" style="display:none">CheckBox is CHECKED!</p>                
                   <p id="text" id="text" style="display:none">CheckBox is CHECKED!</p>                
                   <p id="text" id="text" style="display:none">CheckBox is CHECKED!</p>    
                 

花边的 html 和 javascript 代码,请帮助解决问题...

解决方法

您没有将复选框的 ID 提供给函数。

如果您解析 id,您的代码应该可以工作:

<input type="checkbox" id="chkNIRF" onclick="myFunction('chkNIRF')">

function myFunction(x) {
  // Get the checkbox
  var checkBox = document.getElementById(x);

根据您的评论,这里是一个执行您在评论中要求的小提琴:https://jsfiddle.net/zLvm46jw/1/

为 p 标签添加单独的 id

,

您可以在函数上使用事件参数,然后您可以像这样获取单击复选框的目标:

function myFunction(event) { // Set event argument
  var checkBox = event.target; // Get the clicked checkbox

而在 html 方面,您需要在函数中指定事件:

<input type="checkbox" id="chkNIRF" onclick="myFunction(event)">

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。