如何使用jQuery向生成的元素添加新元素?

时间:2019-11-12 23:20:53

标签: javascript jquery html twitter-bootstrap

我能够为另一个<div>生成一个新的<div>,而那些新的<div>具有一个由计数器生成的自定义ID,我需要代码才能添加新的{ {1}}生成的那些。

代码:

<div>

我已经尝试过了:

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
    <script>
        var counter = 1

        $(document).ready(function () {
            $("#BtnRev").click(function () {
                $("#" + "div" + counter).remove();
                counter = counter - 1;
                if (counter <= 0)
                {
                    counter = 1;
                }
            });


                $("#BtnAdd").click(function () {
                    $("#divMaster").append("<div id='div" + counter + "' class='well'><h4><b>" + counter + ". </b>" + StepTitle.value + "</h4><p>" + Description.value + "</p><button type='button' ID='Btn" + counter + "' class='btn btn - basic'>Add</button></div>");
                    counter = counter + 1;
                    //StepTitle.value = "";
                    //Description.value = "";
                });

            /*$("#" + "Btn" + counter).click(function () {
                $("#" + "div" + counter).append("<div id='div" + counter + 1 + "' class='well'><h4><b>" + counter + ". </b>" + StepTitle.value + "</h4><p>" + Description.value + "</p><button type='button' ID='Btn" + counter + "' class='btn btn - basic'>Add</button></div>");
            });*/
        });
    </script>

    <br />
    <button type="button" ID="BtnAdd" class="btn btn-basic">Add</button>
    <button type="button" ID="BtnRev" class="btn btn-danger">Remove last step</button>
    <hr />
    <label for="StepTitle">Title: </label>
    <input type="text" id="StepTitle" class="form-control" placeholder="Title..." />
    <label for="Description">Description: </label>
    <textarea rows="5" id="Description" class="form-control"></textarea>
    <hr />
    <script src="Test2.js"></script>
    <div id="divMaster" class="well">
        <h4>This is how the steps will look like: </h4>
    </div>

但是它不起作用,预期的输出应该是内部$("#" + "Btn" + counter).click(function () { $("#" + "div" + counter).append("<div id='div" + counter + 1 + "' class='well'><h4><b>" + counter + ". </b>" + StepTitle.value + "</h4><p>" + Description.value + "</p><button type='button' ID='Btn" + counter + "' class='btn btn - basic'>Add</button></div>"); }); 的所有内容,所有这些都是由jquery生成的,如果你们还有其他方法,我将非常乐意将它们检出,在此先感谢!

1 个答案:

答案 0 :(得分:0)

尝试使用:

$("#divMaster").on("click", "#"+"Btn"+counter, function(){
// your code here
});