简体   繁体   English

jquery中动态创建元素的编号

[英]Numeration of dynamically created elements in jquery

I'm trying to create elements (in this case selectors) via a button while also beeing able to delete them via another button:我正在尝试通过一个按钮创建元素(在这种情况下是选择器),同时还可以通过另一个按钮删除它们:

$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".container1");
    var add_button      = $(".add_form_field");

    var x = 1;
    $(add_button).click(function(e){
      e.preventDefault();
      if(x < max_fields){
         x++;
        $(wrapper).append('<div> <fieldset class= "field1"> <select class= "selector1" name="selector*[add numeration here]*"> </select> </fieldset>  <a href="#" class="delete">Delete</a>   </div>'); //add selector box
      }
      else
      {
        alert('You Reached the limits')
      }
      });
      $(wrapper).on("click",".delete", function(e){e.preventDefault(); $(this).parent('div').remove(); x--
        ;})
});

I have no idea, how I can dynamically numerate the selector names from 1 to 10 via the var x.我不知道如何通过 var x 动态计算从 1 到 10 的选择器名称。 Any help would be much appreciated!任何帮助将非常感激!

You can do it like name="selector' + x + '" , but the question is what should happen with the count if i delete 1.?你可以像name="selector' + x + '" ,但问题是如果我删除 1. 计数会发生什么?

Notes:笔记:

if (x < max_fields) { currently only allows you to make 9, so if you want to make 10 use if (x <= max_fields) { if (x < max_fields) {目前只允许你制作 9,所以如果你想制作 10,请使用if (x <= max_fields) {

I've also moved x++ to the end of the if statement so it does not increase the number until the end.我还将x++移到 if 语句的末尾,因此它直到最后才增加数字。

Demo演示

 $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $(".add_form_field"); var x = 1; $(add_button).click(function(e) { e.preventDefault(); var s = FindNext(); if (s > 0) { $(wrapper).append('<div> <fieldset class= "field1"> <select class= "selector1" name="selector' + s + '"> </select> </fieldset> <a href="#" class="delete">Delete</a> </div>'); x++; } else { alert('You Reached the limits') } }); $(wrapper).on("click", ".delete", function(e) { e.preventDefault(); $(this).parent('div').remove(); x--; }) function FindNext() { for (var i = 1; i < max_fields; i++) { if ($('select[name="selector' + i + '"]').length == 0) { return i; } } return 0; } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="add_form_field">add</button> <div class="container1"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM