登录
首页 >  文章 >  前端

创建复选框的一些有效方法

来源:dev.to

时间:2024-10-26 08:34:01 157浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

在文章实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《创建复选框的一些有效方法》,聊聊,希望可以帮助到正在努力赚钱的你。

创建复选框的一些有效方法

创建复选框有 3 种方法:

  1. 通过直接html代码
  2. 通过js代码,创建每个元素、属性、内容并将子元素appendchild到父元素
  3. 通过 js 代码,带有innerhtml 和模板文字

通过直接 html 代码:

<div>
  &lt;input type=&quot;checkbox&quot; name=&quot;color&quot; id=&quot;red&quot;&gt;
  <label for="red">red</label>
 </div>
 <div>
  &lt;input type=&quot;checkbox&quot; name=&quot;color&quot; id=&quot;green&quot;&gt;
  <label for="green">green</label>
 </div>
 <div>
  &lt;input type=&quot;checkbox&quot; name=&quot;color&quot; id=&quot;blue&quot;&gt;
  <label for="blue">blue</label>
 </div>
 <div>
  &lt;input type=&quot;checkbox&quot; name=&quot;color&quot; id=&quot;yellow&quot;&gt;
  <label for="yellow">yellow</label>
 </div>

通过js代码,创建每个元素、属性、内容并将子级appendchild到父级:

<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}">
        &lt;input type=&quot;checkbox&quot; name=&quot;color&quot; id=&quot;${color}&quot; value=&quot;${color}&quot; &gt;
        ${color}</label>
      `
    ).join("");

    root.innerHTML = checkbox;
    </script>
  </body>

今天带大家了解了的相关知识,希望对你有所帮助;关于文章的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>