2013-11-02 36 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