如何在jQuery中单击按钮时添加新文本框?

时间:2014-01-16 10:16:21

标签: jquery html

我正在尝试添加包含4个文本框的新div,单击添加按钮。我必须这样做3次。

问题是我只能第一次做,就是:我不知道如何增加身份证。我正在使用jQuery fadeIn效果。

我找到了一些有用的答案,但我不能用它们来解决我的问题。我找到的最接近的答案是here,但每次都是这样的答案。我想要的只是3次。我的引用是here,这也只是一次。
如何重复3次?

2 个答案:

答案 0 :(得分:2)

做的:

var counter = 1;
$("#addBtn").click(function () {
    if(counter <= 4) {
    var $input = $("<input />", {
        type: "text",
        id: "input_" + (counter),
        name: "some_name",
        value: ""
    });
  $("#container").append($input);
    counter++;
    }
});

演示:: jsFiddle

答案 1 :(得分:0)

你正在寻找这样的东西:

演示 http://jsfiddle.net/abhitalks/r6A7f/2/

标记

<input type="button" id="btn" value="Add" />
<div id="wrap"></div>

JS

var i = 1; // counter to track number of divs
$("#btn").click(function () {
    if (i < 4) { // check if three divs have been created

        // create a div and use index for id
        var $d = $("<div />", {
            id: "d" + i,
            class: 'container'
        });

        // loop for creating 4 inputs
        for (n = 1; n < 5; n++) {
            // create an input and use index for id
            var $i = $("<input />", {
                type: "text",
                id: "i" + n,
                placeholder: "i" + n
            });

            // append the input to the div
            $d.append($i);
        }
        // append the div to the wrapper
        $('#wrap').append($d);

        // increment the index for div creation
        i++;
    }
});