Javascript setattribute - 名称和值不起作用

时间:2016-05-15 20:09:26

标签: javascript dom setattribute

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

2 个答案:

答案 0 :(得分:4)

您需要添加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);

答案 1 :(得分:1)

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

    //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);