체크박스를 만드는 효과적인 방법

Patricia Arquette
풀어 주다: 2024-10-20 06:25:02
원래의
432명이 탐색했습니다.

Some effective ways to create checkboxes

체크박스를 만드는 방법에는 3가지가 있습니다.

  1. 직접 HTML 코드로
  2. JS 코드로 각 요소, 속성, 콘텐츠를 생성하고 부모에 자식 자식을 추가합니다
  3. JS 코드, innerHTML 및 템플릿 리터럴 사용

직접 HTML 코드로 :

<div>
  <input type="checkbox" name="color" id="red">
  <label for="red">Red</label>
 </div>
 <div>
  <input type="checkbox" name="color" id="green">
  <label for="green">Green</label>
 </div>
 <div>
  <input type="checkbox" name="color" id="Blue">
  <label for="Blue">Blue</label>
 </div>
 <div>
  <input type="checkbox" name="color" id="yellow">
  <label for="yellow">Yellow</label>
 </div>
로그인 후 복사

JS 코드를 사용하여 각 요소, 속성, 콘텐츠를 생성하고 부모에 자식 자식을 추가합니다.

<body>
    <div id="root"></div>

    <script>
      const root = document.getElementById("root");
      const colors = ["Red", "Green", "Blue", "Yellow"];
      colors.forEach((color) => {
        // create id
        const id = color;

        // create label
        const label = document.createElement("label");
        label.setAttribute("for", id);

        // create checkbox input element
        const input = document.createElement("input");
        input.type = "checkbox";
        input.name = "color";
        input.id = id;
        input.value = color;

        // appendChild child to parent
        label.appendChild(input);
        label.appendChild(document.createTextNode(color));
        root.appendChild(label);
      });
    </script>
  </body>
로그인 후 복사

JS 코드, innerHTML 및 템플릿 리터럴 사용:

<body>
    <div id="root"></div>

    <script>
      const root = document.getElementById("root");
      const colors = ["Red", "Green", "Blue", "Yellow"];
      const checkbox = colors.map((color)=>`<label for="${color}">
        <input type="checkbox" name="color" id="${color}" value="${color}" >
        ${color}</label>
      `
    ).join("");

    root.innerHTML = checkbox;
    </script>
  </body>
로그인 후 복사

위 내용은 체크박스를 만드는 효과적인 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!