【问题标题】:Even with .on and .delegate, jQuery Not Applying to Ajax Loaded Elements即使使用 .on 和 .delegate,jQuery 也不能应用于 Ajax 加载的元素
【发布时间】:2013-11-02 11:02:10
【问题描述】:

我正在使用 Django,并使用 Django Endless Pagination 和 Twitter 样式加载。尽管我从研究中了解到使用了 .on 和 .delegate ,但我无法让我的 jQuery 代码绑定到新注入的元素。我避免使用 .live 因为它已被弃用,但显然 .on 和 .delegate 在这种情况下应该做同样的事情。

基本上产品搜索结果显示为 Endless Pagination 正在注入的卡片。

相关代码sn-ps:

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

【问题讨论】:

    标签: jquery ajax django django-endless-pagination


    【解决方案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
    

    【讨论】:

    • 完美,谢谢!我没有意识到 document 应该是父级。我之前曾尝试使用带有该语法的单击,但使用直接父容器作为父选择器。
    • @ViciousAmbitious - 乐于助人。也请支持我的回答,因为它很有帮助:) [无耻,不是吗]
    • 我最初尝试过,但它说我需要 15 声望才能这样做。 :^(
    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2011-02-03
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多