问题描述
我已经创建了 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)">