jQuery删除动态创建的元素不起作用

时间:2022-01-08 20:18:33

Here is the code and the jsFiddle http://jsfiddle.net/yh3rynab/1/

这是代码和jsFiddle http://jsfiddle.net/yh3rynab/1/

      var i = 1;
       $('body').on('click', '#add_row', function () {
           if (i >4) {
               alert("No more");
               return;
           }
           $('#fg01_container').append('<div class="form-group" id="fg01_0' + i + '"></div>');
           $('#fg01_0' + i).html('<div class="col-md-2 col-md-offset-4">CONTENT</div>');
           i++;
       });

       $('body').on('click', '#delete_row', function() {
           if (i > 1) {

               $("#fg01_0" + (i - 1)).remove;
               i--;
           }
       });

The code adds fine but it doesn't remove the element that was just created. Please advise!

代码添加正常,但它不会删除刚刚创建的元素。请指教!

2 个解决方案

#1


Remove is a function. call it like remove()

删除是一个功能。称之为remove()

 $("#fg01_0" + (i - 1)).remove();

#2


remove is method and not property in jquery. You should use .remove() instead of .remove

删除是jquery中的方法而不是属性。您应该使用.remove()而不是.remove

 $("#fg01_0" + (i - 1)).remove();

Working Demo

#1


Remove is a function. call it like remove()

删除是一个功能。称之为remove()

 $("#fg01_0" + (i - 1)).remove();

#2


remove is method and not property in jquery. You should use .remove() instead of .remove

删除是jquery中的方法而不是属性。您应该使用.remove()而不是.remove

 $("#fg01_0" + (i - 1)).remove();

Working Demo