0

我有几个这样的元素:

  <div class="image_insert clearfix">
    <label for="userfile3">Image 3</label>
    <input type="file" name="userfile3" id="userfile3">
    <label for="slika_naziv_eng3">Image Title</label>
    <input type="text" name="slika_naziv_eng3" id="slika_naziv_eng3"/>
  </div>

和用于克隆的 JS:

var img_add = $('.img_add');

img_add.on('click', function(){
  var img_ins = $('.image_insert'),
  i = img_ins.length,
  clon = img_ins.first().clone().attr({'class' : 'image_insert clearfix', 'name' : 'userfile' + i}).insertAfter(img_ins.last());
});

我需要更改所有有数字的属性。每次添加新元素时,都需要计算元素的数量,新的数量将是元素数量 + 1。我该怎么做?

4

2 回答 2

0

我从过去写的类似 id 中获取了这个

$("#containerDiv").find("div").each(function(){
    lastVersionNumber = jQuery(this).attr("id").replace(/\D/g, "")/1;
});
newVersionNumber = lastVersionNumber + 1;

# build the new version HTML string
var sHTML = "<div name='mydiv'>";
sHTML += jQuery("#templateCode").html()
sHTML = sHTML.replace(/<input/i, "<input name='v"+newVersionNumber+"_name'");   
sHTML += "</div>";


$("#containerDiv").append(sHTML);
于 2013-01-23T16:54:00.673 回答
0

试试这个:克隆包含新元素,所以,你需要找到你的元素

  <!DOCTYPE html>
  <html>
  <head>
    <title>Clone Elements with Jquery by @MaoAiz + Sasha</title>
  </head>
  <body>
    <button class="img_add">New</button>
    <div class="image_insert clearfix">
        <label for="userfile1" class="img-label">Image 1</label>
        <input type="file" name="userfile1" id="userfile1">
        <label for="slika_naziv_eng1">Image Title</label>
        <input type="text" name="slika_naziv_eng1" id="slika_naziv_eng1"/>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script>
        var img_add = $('.img_add');

        img_add.on('click', function(){
          var img_ins = $('.image_insert'),
          i = img_ins.length + 1;
          clon = img_ins.first().clone().insertAfter(img_ins.last());
          // clon contains the new element, so, you need to find your element
          clon.find("input").first().attr({
            'name'  : 'userfile' + i,
            'id'    : 'userfile' + i
          });
          clon.find("input").last().attr({
            'name'  : 'slika_naziv_eng' + i,
            'id'    : 'slika_naziv_eng' + i
          });
          //plus:
          clon.find(".img-label").text("Image " + i)
          // view you cosole in Chrome Ctrl + Shift + j
          console.log("Elements: " + i)
        });
    </script>
  </body>
  </html>

我在 github 上有一个演示。https://github.com/MaoAiz/Formulario-Dinamico-JQuery

于 2013-01-23T17:29:08.467 回答