2

我使用以下方式在单击“addButton”时添加多个 div,如下小提琴所示:

http://jsfiddle.net/harshmadhani/jpb93/

$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
        if (counter > 2) {
            alert("Only 2 textboxes allowed");
            return false;
        }
        $('<div/>',{'id':'TextBoxDiv' + counter}).html(
          $('<label/>').html( 'Textbox #' + counter + ' : ' )
        )
        .append( $('<input type="text">').attr({'id':'textbox' + counter,'name':'textbox' + counter}) )
        .appendTo( '#TextBoxesGroup' )       
        counter++;
    });

    $("#removeButton").click(function () {
        if (counter == 1) {
            alert("No more textbox to remove");
            return false;
        }
        counter--;
        $("#TextBoxDiv" + counter).remove();
    });
});

我必须使用 html 添加文本并在之后附加它。有没有其他方法可以在 Bootstrap 中解决这个问题?

4

1 回答 1

6

尝试这个

http://jsfiddle.net/jpb93/3/

html

  <div class="form-horizontal">
        <div class="control-group">
            <label class="control-label" for="inputEmail">
                Email</label>
            <div class="controls">
                <input type="text" id="inputEmail" placeholder="Email" />
                </div>
        </div>
    </div>

jQuery:

$(document).ready(function () {

            $("#addButton").click(function () {
                if( ($('.form-horizontal .control-group').length+1) > 2) {
                    alert("Only 2 control-group allowed");
                    return false;
                }
                var id = ($('.form-horizontal .control-group').length + 1).toString();
                $('.form-horizontal').append('<div class="control-group" id="control-group' + id + '"><label class="control-label" for="inputEmail' + id + '">Email' + id + '</label><div class="controls' + id + '"><input type="text" id="inputEmail' + id + '" placeholder="Email"></div></div>');
            });

            $("#removeButton").click(function () {
                if ($('.form-horizontal .control-group').length == 1) {
                    alert("No more textbox to remove");
                    return false;
                }

                $(".form-horizontal .control-group:last").remove();
            });
        });
于 2013-06-22T06:56:55.447 回答