计数div jquery的数量

时间:2016-03-28 22:18:19

标签: javascript jquery

您好我怎么能算出这样的div数量,但由于某种原因它不起作用。 有代码: JSFIDDLE

我希望是这样的:

    There are 1  
    There are 2  
    There are 3
    There are 4...

1 个答案:

答案 0 :(得分:1)

第二个.each()调用无法识别其他.multi-field元素,因为它们在页面加载时不在DOM中。我会做这样的事情:

$('.multi-field-wrapper').each(function() {
    var num = 1;
    var $wrapper = $('.multi-fields', this);

    $(".add-field", $(this)).click(function(e) {
        num++;
      $('.multi-field:first-child', $wrapper)
        .clone(true)
        .appendTo($wrapper)
        .find('span')
        .text('There are ' + num)
        .parent()
        .find('input')
        .val('')
        .focus();
    });

    $('.multi-field .remove-field', $wrapper).click(function() {
        if ($('.multi-field', $wrapper).length > 1)
            $(this).parent('.multi-field').remove();
    }); 
});

将HTML更新为

<form role="form" action="/wohoo" method="POST">
 <label>Stuff</label>
    <div class="multi-field-wrapper">
      <div class="multi-fields">
        <div class="multi-field">
        <span>There are 1</span>
          <input type="text" name="stuff[]">
          <button type="button" class="remove-field">Remove</button>
        </div>
      </div>
    <button type="button" class="add-field">Add field</button>
  </div>
</form>