在动态添加输入元素时,innerHTML不会显示

时间:2015-04-10 19:19:20

标签: javascript innerhtml

我正在尝试使用Javascript添加<input>元素。但是,innerHTML没有显示出来。以下是我的代码:

function addElements()
{
    container = document.getElementById("duration"); //a div container
    var input1 = document.createElement("input");
    var input2 = document.createElement("input");
    input1.type = "number";
    input1.min = "0";
    input1.max = "10";
    input1.required = true;
    input1.innerHTML = "years";
    input2.type = "number";
    input2.min = "0";   
    input2.max = "12";
    input2.required = true;
    input2.innerHTML = "months";
    container.appendChild(input1);
    container.appendChild(input2);
}

此代码的结果仅产生两个不带innerHTML的数字输入字段。我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:3)

输入元素没有可以使用innerHTML设置的内部内容。而是设置value属性:

input1.value = "years";

但是,在您的情况下,您似乎要设置placeholder

input1.setAttribute("placeholder", "years");

或者您也可以设置相应的属性:

input1.placeholder = "years";

答案 1 :(得分:2)

我认为您尝试实现的是 [label] [input] ,在这种情况下,您必须在页面上添加2个新元素。

&#13;
&#13;
function addElements()
{
    container = document.getElementById("duration"); //a div container
    var label1 = document.createElement("label");
    var input1 = document.createElement("input");
    
    var label2 = document.createElement("label");
    var input2 = document.createElement("input");
    
    input1.type = "number";
    input1.min = "0";
    input1.max = "10";
    input1.required = true;
  
    label1.innerHTML = "years";
  
    input2.type = "number";
    input2.min = "0";   
    input2.max = "12";
    input2.required = true;
  
    label2.innerHTML = "months";
    
    container.appendChild(label1);
    container.appendChild(input1);
    container.appendChild(label2);
    container.appendChild(input2);
}

addElements();
&#13;
<div id="duration" />
&#13;
&#13;
&#13;