문제

I'm using Django and with Django Endless Pagination and the Twitter style loading. I cannot get my jQuery code to bind to the newly injected elements, despite using .on and .delegate as I've read from my research. I avoided .live because of its deprecated status, but apparently .on and .delegate should do the same thing in this situation anyway.

Basically product search results appear as cards that Endless Pagination is injecting.

Relevant code snippets:

JS

$(".product-card").on('click',function() {

    cardToggle = $(this).data("switch");

    if (cardToggle==0) {
        // some stuff happens to the card
        $(this).data("switch", 1);
    }else if(cardToggle==1) {
        // some stuff un-happens to the card
        $(this).data("switch", 0);
    }
})

Product List (Template that's Ajax Loaded into Main Page)

{% load static %}
{% load endless %}

{% paginate results %}
{% for result in results %}

    {# divs with class .product-card are created here, code for card removed because of prohibitive length #}

{% endfor %}
{% show_more %}
도움이 되었습니까?

해결책

.click() is just a shorthand of .on('click'). So, even if you use .on() it won't fire. For dynamically created elements, you have to handle event delegation with the following syntax:

(parentselector).on(event,selector,function(){});

So based on that,

$('.product-card').on('click',function() {}); // this is wrong

replace with

$(document).on('click','.product-card',function() {}); // this will work
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top