javascript - 使用 jQuery 插入和删除多个 div

标签 javascript jquery

您好,我知道如何在单击按钮时动态添加 div,以及如何使用 jQuery 删除该 div:

<input type="button" class="adddiv" value="add" />
  <div class="clean">
      msg 
    <button class="close" value="close" >
  </div>

<script>
  $(".adddiv").on("click",function(){
     $('.clean').after('<div class="clean main1">msg<button class="close" value="close" /></div>');
  });

 $(document).on("click",".close",function(){
    $(this).closest('div').remove();
 });

</script>

但是这里我需要限制页面中干净的 div 的最大数量为 5 。如果用户添加超过 5 个 div,我需要限制。

如何做到这一点?

最佳答案

我建议如下,但请注意,我选择将“索引”添加到自定义 data-* 属性,在本例中为 data-index,因为它避免了解析元素的类名来检索该索引的必要性; data-index 值可以使用纯 JavaScript 检索:

var index = HTMLElement.dataset.index;

或者通过 jQuery:

var index = $(element).data('index');

也就是说,我提出的解决方案:

// using the on() method to bind the anonymous function
// of that method as the event-handler for the 'click'
// event fired on the '.adddiv' element:
$('.adddiv').on('click', function() {

  // caching the current '.clean' elements present on
  // the page:
  var cleans = $('.clean'),

  // cloning the first of those elements, including
  // descendants, data and event-handlers, using
  // clone(true, true):
    newClean = $('.clean').eq(0).clone(true, true),

  // retrieving the number of '.clean' elements
  // currently in the document:
    num = cleans.length;

  // setting the 'adddiv' <input> element to be
  // disabled if after the next addition (which
  // is completed within this function) there
  // will be more than 6 '.clean' elements in
  // the document:
  this.disabled = num + 1 >= 6;

  // if the current number of '.clean' elements
  // is less than 6:
  if (num < 6) {

    newClean
      // adding the value of the 'data-index' attribute,
      // JavaScript is zero-indexed so the new index is
      // equal to the current number of 'clean' elements:
      .attr('data-index', num)

      // and then we insert the cloned element after the
      // last of the current '.clean' elements present
      // in the document:
      .insertAfter(cleans.eq(num - 1));
  }
});

// using on() again to bind clicks on the elements
// matched by the supplied selector, delegating the
// event-listening to the document (although the
// closest ancestor element present in the page
// would be a better choice):
$(document).on('click', '.clean > .close', function() {

  // removing the closest ancestor <div> element of
  // the clicked button:
  $(this).closest('div').remove();

  // caching the '.clean' elements in the document
  // after removing the unwanted element:
  var clean = $('.clean');

  // iterating over each of the (remaining) '.clean'
  // elements and updating the 'data-index' property
  // to be equal to the index of insertion:
  clean.attr('data-index', function(i) {

    // it seems likely that the first of the elements
    // should have no index (from what I can see in
    // the question, therefore if i (the index of
    // the current element in the collection) is equal
    // to zero we return an empty string, otherwise we
    // return the index:
    return i === 0 ? '' : i;
  });

  // updating the disabled property of the '.adddiv'
  // <input> element, to reenable if the current
  // number of 'clean' <div> elements is less than 6
  // (though because we enable an element by updating
  // its disabled property it does look a little
  // confusing and 'backwards' almost):
  $('.adddiv').prop('disabled', $('.clean').length >= 6);
});

$('.adddiv').on('click', function() {
  var cleans = $('.clean'),
    newClean = $('.clean').eq(0).clone(true, true),
    num = cleans.length;
  this.disabled = num + 1 >= 6;

  if (num < 6) {
    newClean.attr('data-index', num).insertAfter(cleans.eq(num - 1));
  }
});

$(document).on('click', '.clean > .close', function() {
  $(this).closest('div').remove();

  var clean = $('.clean');
  clean.attr('data-index', function(i) {
    return i === 0 ? '' : i;
  });

  $('.adddiv').prop('disabled', clean.length >= 6);
});
/* hiding the close button if there is
   only one <div> present within the
   common parent */
div:only-of-type button.close {
  display: none;
}

[data-index]::after {
  content: attr(data-index);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="adddiv" value="add" />
<div class="clean">
  msg
  <button class="close">Close</button>
</div>

JS Fiddle demo .

引用资料:

关于javascript - 使用 jQuery 插入和删除多个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202778/

相关文章:

javascript - 从 jQuery 1.6.2 升级到 1.8.1 后,jQuery 自动完成定位错误

javascript - 如何获取选中的动态复选框的值

javascript - 设置 div 的 HTML 以包含其自己的唯一值

javascript - 如何使用API​​调用(jssor_slider1.$GoTo(N))

javascript - 将 jsfiddle 传输到 Dreamweaver

javascript - 在 map 中的特定索引处插入

Javascript 变量初始化类型

jquery - 使用jquery的窗口滚动效果

javascript - 如何部分替换 Underscore.js 模板,或如何从模板创建模板

javascript - Bootstrap 不关闭菜单