使用javascript增加按钮

时间:2014-07-22 14:30:29

标签: javascript

这是我的代码:

JS CODE

var currentindex = 0;
function addInput() {

    var lastinput = document.getElementById('input' + currentindex);
    if(lastinput.value != '') {
        var container = document.getElementById('inputcontainer');
        var newinput = document.createElement('input');
        currentindex++;
        newinput.type = "text";
        newinput.name = 'input' + currentindex;
        newinput.id   = 'input' + currentindex;
        newinput.onkeyup = addInput;
        container.appendChild(newinput);
    }
}

HTML CODE

<html>
<body>
<div id="inputcontainer">
<input type="text" name="input0" id="input0" onkeyup="addInput();" />
<button type="button">clickme</button>
</div>
</body>
</html>

此处,新输入框每次都会递增,但按钮不会根据输入框递增。我该怎么做才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

正如其他人在评论中所述,你错过了按钮附加部分。因此,您需要创建新的button并将其附加到容器

var container = document.getElementById('inputcontainer');
var newinput = document.createElement('input');
var newbutton = document.createElement('button');

currentindex++;
newinput.type = "text";
newinput.name = 'input'+currentindex;
newinput.id = 'input'+currentindex;
newbutton.innerHTML="clickme";
newinput.onkeyup = addInput;
container.appendChild(newinput);
container.appendChild(newbutton);

这是Working JsFiddle