2013-11-02 35 views
1

我使用Django,并与Django无尽的分页和Twitter风格加载。尽管使用.on和.delegate,但我无法让我的jQuery代码绑定到新注入的元素,正如我从我的研究中读到的。我避免了因为它被弃用的地位而活跃,但显然.on和.delegate无论如何都应该在这种情况下做同样的事情。即使与.on和.delegate,jQuery不适用于Ajax加载元素

基本上产品搜索结果显示为无尽分页正在注入的卡片。

相关代码片段:

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); 
    } 
}) 

产品列表(模板的AJAX加载到主页)

{% 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 %} 

回答

1

.click()只是一个.on('click')简写。所以,即使你使用.on()它也不会触发。 对于动态创建的元素,你必须处理事件代表团的语法如下:

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

所以此基础上,

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

更换

$(document).on('click','.product-card',function() {}); // this will work 
+0

完美,谢谢!我没有意识到_document_应该是父母。我曾尝试使用具有该语法的click,但使用直接父容器作为父选择器。 – DiscRiskandBisque

+0

@ViciousAmbitious - 很乐意提供帮助。请也upvote我的答案,因为它是有益的:) [无耻的,是不是我] – Krishna

+1

我最初尝试,但它说我需要15声望这样做。 :^( – DiscRiskandBisque