JS append增加

点击一个增加按钮,每次新增一个div,上限为5个,当div个数达到第4个时,点击增加按钮,新增第五个div,同时增加按钮disabled,被禁用。

html代码如下:


   <div id="div_add"></div>

   <input type="button" id="btn1" value="增加"/>

JS代码如下:我是依据div的个数来判断的,我的代码问题是生成了第5个div,再次点击增加按钮,这时按钮才被禁用。


 $(function () {

    var addHTML = '<div class="div_list"></div>';

    $("#div_add").append(addHTML);

    $("#btn1").click(function () {

        var aa = $(".div_list").length;

        console.log(aa);

        if (aa < 5) {

            $("#div_add").append(addHTML);

        } else if (aa > 5) {

            $("#btn1").attr("disabled", "disabled");

            return true;

        }

    });

})

JS初学者,请大神指点下


料青山看我应如是
浏览 1753回答 2
2回答

蝴蝶不菲

简单写了一下,凑合看css:#div_add{&nbsp; &nbsp; &nbsp; border: 1px solid #000;&nbsp; &nbsp; &nbsp; width: 500px;&nbsp; &nbsp; }&nbsp; &nbsp; .div_list{&nbsp; &nbsp; &nbsp; width: 200px;&nbsp; &nbsp; &nbsp; height: 20px;&nbsp; &nbsp; &nbsp; background-color: greenyellow;&nbsp; &nbsp; &nbsp; border: 1px solid #ccc;&nbsp; &nbsp; }html<input type="button" id="btn1" value="增加"/><input type="button" id="btn2" value="清空"/><div id="div_add"></div>js:<script src="../jquery.min.js"></script>var addHTML = '<div class="div_list"></div>';&nbsp; //$('#div_add').append(addHTML);&nbsp; var time = 0;&nbsp; $('#btn1').click(function (e) {&nbsp; &nbsp; time++;&nbsp; &nbsp; if(time < 6){&nbsp; &nbsp; &nbsp; $('#div_add').append(addHTML);&nbsp; &nbsp; }&nbsp; &nbsp; if(time === 5){&nbsp; &nbsp; &nbsp; $(this).attr("disabled", "disabled");&nbsp; &nbsp; }&nbsp; });&nbsp; $('#btn2').click(function (e) {&nbsp; &nbsp; $('#div_add').empty();&nbsp; &nbsp; $('#btn1').removeAttr('disabled');&nbsp; &nbsp; time = 0;&nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript