具有项目特定功能的Django模板循环的最佳实践?

Bee*_*ees 1 javascript django jquery

我有一个有效的解决方案,但我想知道最好的方法.

我有一个模板,生成一个像这样的项目表:

{% for item in item_list %}
    {{ item.name }}: <button onclick="doSomething({{item.id }})">Click Me!</button>
{% endfor %}

<script>
function doSomething(item_id) {
    // Do stuff here
    // Is actually an ajax request which sends the item's id
}
</script>
Run Code Online (Sandbox Code Playgroud)

这很好用,但是我知道在Javascript中使用监听器是最好的做法,而不是onlick.

有一个函数并item.id根据单击的按钮动态注入函数的最佳方法是什么?

我能想到的唯一方法是item_list在Javascript中再次循环并为每个item按钮创建一个函数.这是最好的方法吗?

{% for item in item_list %}
    {{ item.name }}: <button id="btn-{{ item.id }}">Click Me!</button>
    {% endfor %}

<script>
{% for item in item_list %}
    jQuery("#btn-{{ item.id }}").click(function() {
      // Do the stuff with {{ item.id }}
    });
{% endfor %}
</script>
Run Code Online (Sandbox Code Playgroud)

在我看来,根据这个长度item_list可能会产生很多Javascript.这是一个问题吗?有没有更好的办法?

kar*_*ikr 5

我会这样做:

{% for item in item_list %}
    {{ item.name }}: <button class="button-item" id="btn-{{item.id}}">Click Me!</button>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

在jquery中,

jQuery(document).on('click', ".button-item", function(){
    var $this = $(this);
    var id = $this.attr('id').split('-')[1];
    //do stuff with this id or $this element
});
Run Code Online (Sandbox Code Playgroud)

在这里,您的侦听器正在侦听button-item应用于生成的所有项节点的单个类.单击,获取单击节点的ID.