以下为ChatGPT自动生成的解答,正确与否请自行判断。

BFE.devAI解答 - 前端系统设计
20. Implement nested checkboxes

To implement nested checkboxes, we can use HTML, CSS, and JavaScript. Here is a possible solution:

  1. HTML structure:
<div class="checkbox">
  <input type="checkbox" id="parent">
  <label for="parent">Parent checkbox</label>
  <ul>
    <li>
      <input type="checkbox" id="child1">
      <label for="child1">Child 1</label>
    </li>
    <li>
      <input type="checkbox" id="child2">
      <label for="child2">Child 2</label>
      <ul>
        <li>
          <input type="checkbox" id="grandchild1">
          <label for="grandchild1">Grandchild 1</label>
        </li>
        <li>
          <input type="checkbox" id="grandchild2">
          <label for="grandchild2">Grandchild 2</label>
        </li>
      </ul>
    </li>
    <li>
      <input type="checkbox" id="child3">
      <label for="child3">Child 3</label>
    </li>
  </ul>
</div>
  1. CSS styles:
.checkbox ul {
  margin-left: 20px;
}
  1. JavaScript code:
const parentCheckbox = document.getElementById('parent');
const childCheckboxes = document.querySelectorAll('#parent li input[type="checkbox"]');

function updateParentCheckbox() {
  if (Array.from(childCheckboxes).every(c => c.checked)) {
    parentCheckbox.checked = true;
    parentCheckbox.indeterminate = false;
  } else if (Array.from(childCheckboxes).every(c => !c.checked)) {
    parentCheckbox.checked = false;
    parentCheckbox.indeterminate = false;
  } else {
    parentCheckbox.checked = false;
    parentCheckbox.indeterminate = true;
  }
}

parentCheckbox.addEventListener('click', () => {
  childCheckboxes.forEach(c => {
    c.checked = parentCheckbox.checked;
  });
  updateParentCheckbox();
});

childCheckboxes.forEach(c => {
  c.addEventListener('click', () => {
    updateParentCheckbox();
  });
});

updateParentCheckbox();

The updateParentCheckbox function checks if all the child checkboxes are checked, unchecked, or in an indeterminate state, and updates the parent checkbox accordingly. The event listeners handle the clicks on the parent and child checkboxes, and update the parent checkbox and the indeterminate state as necessary. The updateParentCheckbox function is called once at the beginning to initialize the state.