Javascript setattribute - 名称和值不起作用

jav*_*ava 5 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>
Run Code Online (Sandbox Code Playgroud)

Luk*_*uka 5

您需要添加一个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);
Run Code Online (Sandbox Code Playgroud)