Javascript setattribute - 名称和值无效

Javascript setattribute - name and value not work

当我实现此代码时 - 复选框的名称不会在浏览器中显示在复选框旁边 - 只是复选框本身。这是什么原因?我是否错误地使用了 setattribute-function?

<script type="text/javascript">

    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "car");
    x.setAttribute("name", "vehicle");
    document.body.appendChild(x);

</script>

您需要添加一个 label 元素:

var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("value", "car");
x.setAttribute("name", "vehicle");
document.body.appendChild(x);

var label = document.createElement("label");
label.textContent = "vehicle";
document.body.appendChild(label);

您应该在动态创建复选框时为复选框创建标签并将其附加到正文

    //create checkbox
    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "car");
    x.setAttribute("name", "vehicle");

    //create label
    var y = document.createElement("label");
    y.innerHTML = "Here goes the text";

    //Append Them to body
    document.body.appendChild(x);
    document.body.appendChild(y);