2016-05-15 51 views
3

當我實現此代碼時 - 複選框的名稱將不會顯示在瀏覽器旁邊的複選框 - 只是複選框本身。這是什麼原因?我是否錯誤地使用setattribute-function?Javascript 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> 
+1

代碼工作罰款:https://jsfiddle.net/ag663kw8/'name'不會在您的''旁邊添加文字'車輛';這就是'

+0

您是否嘗試添加標籤? – Ygalbel

回答

3

您需要添加一個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); 
+0

A [* label *](http://w3c.github.io/html/sec-forms.html#the-label-element)通過使用表單控件上的ID與*爲標籤上的*屬性,或將標籤包裹在控件上。只需將標籤放置在控件旁邊即可,與使用跨度或純文本節點相同。 – RobG

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