如何在动态添加的复选框中添加标签或文本?

时间:2019-12-21 21:39:27

标签: javascript google-chrome-extension

问题

如何将标签动态添加到我的复选框?下面的代码呈现一个复选框,而不是一个标签。对于上下文,我正在构建chrome扩展程序。

Image of the checkbox, without a label

代码

  • 在内容脚本中

    var check = document.createElement("input");
          check.id = "checkbox1";
          check.type = "checkbox";
          check.style.marginLeft = "10%";
          check.style.marginBottom = "10%";
          check.style.marginTop = "-8%";
          check.innerHTML = "Goal Accomplished";//THIS TEXT DOES NOT APPEAR.
            //if the checkbox is clicked, remove the sticky note.
          check.href="javascript:removeSticky()"
          check.addEventListener('change', () => {
                if (check.checked) {
                    removeSticky();
                } else {
                    // nothing
                }
          });
    
            //appending the checkbox to the sticky note div
          document.getElementById("sticky").append(check);
    
    
            //trying to add a label to the checkbox, which does not work.
          var newlabel = document.createElement("label");
          newlabel.innerHTML = "Here goes the text";
          newlabel.color = "black";
          document.getElementById("checkbox1").append(newlabel);//THIS RESULTS IN NOTHING
    
          document.body.append(newlabel);//To test if the label has been made.
    
    • 结果:

Image of the result of the last line of code

1 个答案:

答案 0 :(得分:0)

开始工作!关键不是要附加到复选框,而是要附加到其父div。

            var checkSpan = document.createElement("span");
                checkSpan.id="checkSpan";
                checkSpan.style.position = "absolute";
                checkSpan.style.display = "inline-block";
                checkSpan.style.float = "left";
                checkSpan.style.float = "left";

            document.getElementById("sticky").append(checkSpan);

            var labelSpan = document.createElement("span");
                labelSpan.id="labelSpan";

                labelSpan.style.display = "inline-block";

                labelSpan.style.marginLeft = "20%";
                labelSpan.style.marginBottom = "10%";

            document.getElementById("sticky").append(labelSpan);


              var check = document.createElement("input");
              check.id = "checkbox1";
              check.type = "checkbox";

              document.getElementById("checkSpan").append(check);

              var newlabel = document.createElement("label");
              newlabel.style.display = "inline";
              newlabel.innerHTML = "Goal Accomplished!";
              newlabel.style.marginBottom = "10%";
              document.getElementById("labelSpan").append(newlabel);