删除动态填充的<仅在数组包含奇数项时起作用

remove dynamically populated <li> only works when the array contains odd number of items

本文关键字:包含奇 数组 起作用 填充 动态 删除      更新时间:2023-09-26

项目实例:http://jsfiddle.net/k3buckuc/

enterItem = []
itemNumber = 0
// mark item as checked and add delete functionality 
function check() {
    $('#itemsListed').on('click', 'li', function() {    
        $(this).toggleClass('checked');
        $(this).append('<hr />');
        $(this).append('<button class="trash">X</button>');
        $(this).not('.checked').find('hr').remove();
        $(this).not('.checked').find('button').remove();
        // enable trash or delete functionality individual list items
        $('.trash').on('click', function() {
            $(this).closest('li').remove();
        });
    });
}

只有当itemNumber为奇数或enterItem包含奇数项时才正确执行

查看检查我如何将项推入数组和我的增量技术的提琴

这是因为您不断地绑定同一个事件。每次添加项时,将为click事件绑定另一个处理程序。

当您添加了偶数个项目时,就会添加偶数个事件处理程序。当您单击某项时,第二个处理程序将撤消第一个处理程序所做的操作。

例如,当您有十个项目时,事件处理程序将被调用十次。由于最终结果与调用事件处理程序0次相同,因此看起来没有发生任何事情。

只需绑定一次事件处理程序,而不是每次添加项时都绑定。

就这样做:

 //   function check() {
        $('#itemsListed').on('click', 'li', function() {    
            $(this).toggleClass('checked');
            $(this).append('<hr />');
            $(this).append('<button class="trash">X</button>');
            $(this).not('.checked').find('hr').remove();
            $(this).not('.checked').find('button').remove();
            // enable trash or delete functionality individual list items
            $('.trash').on('click', function() {
                $(this).closest('li').remove();
            });
        });
   // }
将绑定移到check()函数之外;