jquery动态生成input,并且限制生成个数

2019-07-10 17:42:06 浏览数 (1)

写一个小的demo,具体是点击添加按钮,会自动生成input输入框,并且根据要求限制生成的input输入框的个数。

大致效果如下所示:

代码语言:javascript复制
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <style>
            .form-group{
                
                height: 26px;
            }
            .control-label{
                margin-top:8px;
            }
            #fat-btn{
                margin-left: 12px;
            }
        </style>
    </head>
    <body>
        <div class="row">
            <div class="col-md-12 col-sm-12  col-xs-12">
                <div class="form-group">
                    <label class="col-sm-1 control-label">检测时间</label>
                    <div class="col-sm-4" style="width: 109px;">
                        <input type="text" value="09:00" class="form-control sleepStart" ></input>
                    </div>
                    <div class="col-sm-4" style="width: 109px;">
                        <input type="text" value="17:30" class="form-control sleepStop"  ></input>
                    </div>
                </div>
            </div>
        </div>
        <div id="time"></div>
        <div class="row">
            <div class="col-md-12 col-sm-12  col-xs-12">
                <div class="form-group">
                    <button id="fat-btn" class="btn btn-primary" type="button">添加
                </button>
                </div>
            </div>
        </div>
    </body>
    <script>
        $(function() {
            $("#fat-btn").click(function() {
                if($('.sleepStart').length > 2) {
                    return alert('超过三个了')
                } else {
                    var htm = "";
                    htm  = "<div class='row'>";
                    htm  = "<div class='col-md-12 col-sm-12  col-xs-12'>";
                    htm  = "<div class='form-group'>";
                    htm  = "<label class='col-sm-1 control-label'>检测时间</label>";
                    htm  = "<div class='col-sm-4' style='width: 109px;'>";
                    htm  = "<input type='text' value='09:00' class='form-control sleepStart'></input></div>";
                    htm  = "<div class='col-sm-4' style='width: 109px;'>";
                    htm  = "<input type= 'text' value='17:30' class='form-control sleepStop'></input>";
                    htm  = "</div></div></div></div>";
                    $('#time').append(htm);
                }
            });

        });
    </script>   
</html>

原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1 90后前端妹子,爱编程,爱运营,文艺与代码齐飞,魅力与智慧共存的程序媛一枚。

0 人点赞