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