Javascript setattribute-名称和值无效

Javascript setattribute - name and value not work

本文关键字:无效 setattribute- Javascript      更新时间:2023-09-26

当我实现这段代码时,复选框的名称不会与复选框一起显示在浏览器中,只是复选框本身。这是什么原因?我是否错误地使用了setattribute函数?

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