簡體   English   中英

復選框切換內容部分不適用於所有復選框

[英]Checkbox toggle content section not working for all checkboxes

我已經創建了 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)">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM