第一次使用Jquery clone div,停止用户克隆次数超过6次

时间:2017-04-12 12:53:13

标签: javascript jquery html clone

我正在尝试为现有div创建克隆div。克隆正在运行,并允许用户通过单击按钮克隆div。现在我想要验证的是,只允许用户克隆div最多6次,如果可能的话,显示消息"你不能再添加项目"

  <div id ="specdiv ">
         <fieldset class="fieldset">
              <legend class="legend">Question Specification</legend>
                 <div class="editor-label">
            @Html.LabelFor(model => model.OfferedAnswer)
        </div>
            <div class ="answerchoice1" id="">
         <div class="editor-field">
           @Html.TextAreaFor(model => model.OfferedAnswer.AnswerText)




        </div>
                </div>

             </fieldset>


    </div>
 <button id="quesId" class="mini-button" type =" button">+</button>

 $(document).ready(function () {
    $('button').click(function () {
        //$('.answerchoice1').before($('.answerchoice1').clone())
        var $target = $('.answerchoice1').find('div.editor-field:first');
        $target.clone().appendTo('.answerchoice1');
        var tID = $(this).attr(".answerchoice1").split(/ _/);
        //console.log($('.example-1').html());
    })

})

1 个答案:

答案 0 :(得分:1)

这样的事情就是你所追求的:

$(document).ready(function () {
    $('button').click(function () {
        if($('.editor-field').length >= 6){
        alert('No more than 6!');
        return false;
        }
        //$('.answerchoice1').before($('.answerchoice1').clone())
        var $target = $('.answerchoice1').find('div.editor-field:first');
        $target.clone().appendTo('.answerchoice1');
        var tID = $(this).attr(".answerchoice1").split(/ _/);
        //console.log($('.example-1').html());
    })

})

工作小提琴: https://jsfiddle.net/on3kj4hp/

希望它有所帮助!