1

我如何更改此代码以限制最多 25 次。用户可以删除块并再次添加它,始终最多 25 次

HTML

holderBlock - 它拥有一切

repeaterIngredient - 这是克隆的 div

<div id="holderBlock">

<div class="repeaterIngredient">                         

    <div class="row grid-12-12">
        <label for="extens_ingredientName" title="Tooltip Information">Ingredient name<span class="entity">T4094</span><em class="form-req"><img src="../../Content/Images/ico_transparent.png" alt="required" /></em></label>
        <textarea name="extens_ingredientName" id="extens_ingredientName" class="textArea70"></textarea>
    </div>

    <div>
        <input type="button" value="Remove Ingredient" title="Remove Ingredient" class="formee-button right remove_ingredient">
        <input type="button" value="Add New Ingredient" title="Add New Ingredient" class="formee-button right add_ingredient">
    </div> 

</div>

jQuery

此代码用于克隆repeaterIngredient类并增加内部所有表单元素的 for、name 和 id 用户可以创建另一个repeaterIngredient并将其删除,但我需要更改此代码,以便在达到 25 个 div 时停止并正常工作如果用户删除 div 并再次添加它

var template = $('#holderBlock .repeaterIngredient:first').clone(),

        ingredientsCount = 1;

        var addIngredient = function () {

            ingredientsCount++;

            var repeaterIngredient = template.clone().find(':input').each(function () {

                var newId = this.id.substring(0, this.id.length - 1) + ingredientsCount;

                $(this).prev().attr('for', newId); // update label for (assume prev sib is label)

                this.name = this.id = newId; // update id and name (assume the same)

            }).end() // back to .repeaterIngredient

                .attr('id', 'repeaterIngredient' + ingredientsCount) // update repeaterIngredient id

                .appendTo('#holderBlock'); // add to container
        };

        //EXECUTE FUNCTION
        $('input.add_ingredient').live("click", addIngredient); // attach event

        // HIDE FIRST REMOVE BUTTON
        $('#holderBlock input.remove_ingredient:first').hide();

        // DELETE CREATED BLOCK
        $('input.remove_ingredient').live("click", function () {
            //console.log($(this).parent());
            $(this).parent().parent().hide();
            return false;
        });
4

1 回答 1

1

在创建之前,您需要计算可见 div:

if ($('.repeaterIngredient:visible').count() > 25)
  return;

你还需要添加类repeaterIngredient

...
.attr('id', 'repeaterIngredient' + ingredientsCount)
.addClass('repeaterIngredient')
.appendTo('#holderBlock');
...

如果您删除.repeaterIngredient而不是隐藏,您可以简化优化脚本:

$(this).parent().parent().remove();

而且您不需要计算可见项目:

if ($('.repeaterIngredient').count() > 25)
  return;

PS我不测试这段代码。我希望对你有所帮助。

于 2012-08-16T12:30:31.953 回答