简体   繁体   English

添加子div时JS事件监听器停止工作,只有最后一个div事件监听器起作用

[英]JS event listener stops working when child divs are added, only last div event listener works

I'm working on a arbitrary project, and I'm trying to only use vanilla JS because I'm a masochist. 我正在从事一个任意项目,并且由于我是受虐狂,所以我尝试仅使用Vanilla JS。 I have it set up to display a list of items, each with a button to add the item to to the 'cart'. 我将其设置为显示项目列表,每个项目都有一个将项目添加到“购物车”的按钮。 When they get added to the cart each a new div containing the item information and a button is pushed into the sidebar div. 当它们被添加到购物车时,每个新的div都包含项目信息和一个按钮,该div被推入侧栏div中。 When the button for the add item to cart is pushed it makes a call to the function that adds the event listener to the remove item button which have their own unique id's. 当按下向购物车添加商品的按钮时,它会调用将事件侦听器添加到具有自己唯一ID的删除商品按钮的函数。 My problem is once more items are added to the cart, only the last item's remove button works. 我的问题是,一旦有更多物品添加到购物车,只有最后一项的“删除”按钮起作用。 Here's the relevant bit of JS: 这是JS的相关部分:

This sets the eventListeners for the add to cart buttons: 这将为添加到购物车按钮设置eventListeners:

function setupItemClickHandlers(items) {
    var buttons = document.getElementsByClassName('add-cart');
    var i; 

    function generateItemClickHandler(itemNumber) {
        return function clickHandler() {
            // does things to the objects
            setupCartItemClickHandlers(itemCartNum);
        }
    }

    for(i = 0; i < buttons.length; i++){
        buttons[i].addEventListener('click', generateItemClickHandler(i));
    }
}

And the code that sets the remove items buttons event listeners (Note: I added the format function to String's prototype, the unique numbers are getting inserted there): 设置删除项按钮的按钮会监听事件(注意:我在String的原型中添加了format函数,唯一的数字已插入其中):

function setupCartItemClickHandlers(itemNum){
    var elCartItem = document.getElementById('item-{0}'.format(itemNum));
    var removeButton = document.getElementById('remove-{0}'.format(itemNum));

    function generateRemoveClickHandler(itemNum) {
        return function clickHandler() {
            // Does what it needs to do
        }
    }

    removeButton.addEventListener('click', generateRemoveClickHandler(itemNum));
}

Here's the fiddle 这是小提琴

您只能使用event.target和event.srcElement为购物车的父项创建(像jQuery live / on)事件监听器一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM