简体   繁体   中英

Javascript - click event doesn't work anymore after “infinite scroll”

So I have an infinite scroll system in my javascript. First it loads 50 items, then if you scroll down a bit then another 50 items. The problem with this is that, if you scroll down and click on item nothing happens. If you first load the page and there's the 50 items, if you click on the one of the items, then it goes red and becomes selected , but after you load the other amount, then the clicking doesn't work anymore.

Here's my code for the `infite scroll:

var perPage = 50;

function paginate(items, page) {
    var start = perPage * page;
    return items.slice(start, start + perPage);
}
var condition = '';

function renderItems(pageItems) {
    pageItems.forEach(function(item, index, arr) {
        var message = 'BitSkins Price: $' + item.bprice + '';
        if (item.price != null) {
            if (item.bprice == '') {
                message = 'Item never sold on BitSkins!';
            }
            if (item.name != 'Operation Phoenix Case Key' && item.name != 'CS:GO Case Key' && item.name != 'Winter Offensive Case Key' && item.name != 'Revolver Case Key' && item.name != 'Operation Vanguard Case Key' && item.name != 'Operation Wildfire Case Key' && item.name != 'Shadow Case Key' && item.name != 'Operation Breakout Case Key' && item.name != 'Chroma Case Key' && item.name != 'Huntsman Case Key' && item.name != 'Falchion Case Key' && item.name != 'Chroma 2 Case Key') {
                $("#inventory").html($("#inventory").html() + "<li class='col 2 zoomIn animated' style='padding:8px;font-weight:bold;font-size:16px'><div class='card item-card waves-effect waves-light' style='margin:0%;min-height:295px;width:245.438px;border-radius: 15px;' id='" + item.id + "'><div class='iteam' style='text-decoration: underline;text-align: left'>" + item.name + "</div><div class='condition' style='text-align: left;text-size:13px'>" + item.condition + "</div><div class='center-align' style='padding:6%'><img title=\"" + item.originalname + "\" draggable='false' src='https://steamcommunity-a.akamaihd.net/economy/image/" + item.iconurl + "/200fx200'><div class 'floatvalue'>Float: 0.11503319442272186<div class='bitskinscomp' style='font-weight: normal;font-size:12px'>" + message + "</div><div class='buyer-price center-align'>$" + numberWithCommas(item.price) + "</li></div></div>");
            }
        }
    });
}
var win = $(window);
var page = 0;
renderItems(paginate(items, page));
win.scroll(function() {
    if ($(document).height() - win.height() == win.scrollTop()) {
        page++;
        renderItems(paginate(items, page));
    }
});

Here's my code for my item click

            $(".item-card").click(function() {
            var itemnume = $(this).find("img").attr("title");
            var buyerprice = $(this).find(".buyer-price").html();
            var replaced = itemnume.split(' ').join('_');
            replaced = replaced.split('(').join('');
            replaced = replaced.split(')').join('');
            replaced = replaced.split('|').join('');

            if ($(this).hasClass('selected-item')) {
                $("#" + replaced).last().remove();
            } else {
                var cart_item = $("<div id=" + replaced + ">" + itemnume + "</div>");
                $("#itemcart").append(cart_item);
                $("#itemcart div").each(function() {
                    if ($(this).children().length > 0) {

                    } else {
                        $(this).append($("<span> " + buyerprice + "</span>"));
                    }
                });
                var self = $(this);
                cart_item.on('click', 'span', function() {
                    $(this).parent().remove()
                    self.removeClass("red lighten-1 white-text selected-item");
                    calculateTotal();
                });
            }
            $(this).toggleClass("red lighten-1 white-text selected-item");

            calculateTotal();
        });

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or replacing the content .

General Syntax

$(document).on('event','selector',callback_function)

Example

$("#inventory").on('click', ".item-card", function(){
    //Your code
});

Additionally you can use append()

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

$("#inventory").append("<li class='col 2 zoomIn animated' style='padding:8px;font-weight:bold;font-size:16px'><div class='card item-card waves-effect waves-light' style='margin:0%;min-height:295px;width:245.438px;border-radius: 15px;' id='" + item.id + "'><div class='iteam' style='text-decoration: underline;text-align: left'>" + item.name + "</div><div class='condition' style='text-align: left;text-size:13px'>" + item.condition + "</div><div class='center-align' style='padding:6%'><img title=\"" + item.originalname + "\" draggable='false' src='https://steamcommunity-a.akamaihd.net/economy/image/" + item.iconurl + "/200fx200'><div class 'floatvalue'>Float: 0.11503319442272186<div class='bitskinscomp' style='font-weight: normal;font-size:12px'>" + message + "</div><div class='buyer-price center-align'>$" + numberWithCommas(item.price) + "</li></div></div>");

instead of

$("#inventory").html($("#inventory").html() + "<li class='col 2 zoomIn animated' style='padding:8px;font-weight:bold;font-size:16px'><div class='card item-card waves-effect waves-light' style='margin:0%;min-height:295px;width:245.438px;border-radius: 15px;' id='" + item.id + "'><div class='iteam' style='text-decoration: underline;text-align: left'>" + item.name + "</div><div class='condition' style='text-align: left;text-size:13px'>" + item.condition + "</div><div class='center-align' style='padding:6%'><img title=\"" + item.originalname + "\" draggable='false' src='https://steamcommunity-a.akamaihd.net/economy/image/" + item.iconurl + "/200fx200'><div class 'floatvalue'>Float: 0.11503319442272186<div class='bitskinscomp' style='font-weight: normal;font-size:12px'>" + message + "</div><div class='buyer-price center-align'>$" + numberWithCommas(item.price) + "</li></div></div>");

Try replacing your

$(".item-card").click(function() { ...

With

$(document).on("click", ".item-card", function(){ ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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