【问题标题】:Python3 + Django : How to use Jquery in render_to_string template?Python3 + Django:如何在 render_to_string 模板中使用 Jquery?
【发布时间】:2018-06-04 18:59:33
【问题描述】:

我的酱在下面。

使用 render_to_string 创建的模板中的元素不是 Jquery 控件。

▶ index.html

{% extends 'common/base.html' %}
{% block contents %}
<section>
    <div class="main-goods-area">
        <div class="container" id="prod_list">
        </div>
    </div>
</section>
{% endblock %}

{% block jquery %}
    <script src="{% static 'js/index.js' %}"></script>
{% endblock %}

▶ index.js

$(function() {
    show_inf_list('0','0','0','0','0');
    function show_inf_list(section, selection, ordering, start, limit){
        $.ajax({
            url:'/campaign/list/',
            data:{
                'campaign_section': section,
                'selection_type': selection,
                'ordering_type': ordering,
                'start': start,
                'limit': limit
            },
            dataType:'json',
            success: function (data) {
                $('#prod_list').html(data.campaign_list);
            }
        });
    }

    $('a[name=btn_like]').on('click', function (e) {
        e.preventDefault()
        console.log('a');
        return false;
    });
});

▶views.py

def ...
    data['campaign_list'] = render_to_string(
        'main/include/prod_list.html',
        context=context,
        request=request
    )
    return JsonResponse(data)

▶ prod_list.html

<div class="ic-area">
    <ul>
        <li>
            <a href="" name="btn_like" data-id="{{ campaign.id }}">
                {% if user.influencer in campaign.like_users.all %}
                    <i class="ic_heart_small active"></i>
                {% else %}
                    <i class="ic_heart_small"></i>
                {% endif %}
            </a>
        </li>
    </ul>
</div>

我想要控制'btn_like'元素

但是,我无法控制 'a[name=btn_like]'

如何在 render_to_string 模板的元素中使用 Jquery 控件?

【问题讨论】:

    标签: javascript jquery python django render-to-string


    【解决方案1】:

    问题是您已经在'a[name=btn_like]' 上设置了处理程序,但它是在 DOM 就绪时分配的;因此通过 Ajax 加载的新元素不会链接到处理程序。相反,将处理程序分配给更高的元素并使用委托。

    $('#prod_list').on('click', 'a[name=btn_like]', function(data) ...
    

    【讨论】:

    • 这对我很有用。谢谢。
    猜你喜欢
    • 2013-08-09
    • 2015-09-07
    • 1970-01-01
    • 2017-04-21
    • 2011-12-03
    • 2021-12-11
    • 2018-08-28
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多