首页 > 解决方案 > How to generate a unique div id for django objects displayed in template

问题描述

I am working on a Django project. I have a template which displays all the available posts. Users can like a post. Everything is working fine. But I am facing a problem. Since I am using ajax to change the status of the like button when a user clicks on it, I noticed that all the like buttons of the displayed posts object are affected, when a user clicks on the like button of one of the displayed posts. I want changes to occur just on the like button the user has clicked. Not all the like buttons of the displayed post object

Example of my HTML template looks something of this sort.

{% for post in allpost %} <!--for loop to get all post objects in data base-->
{{post.tittle}}
{{post.content}}
{{post.type}}

<!-- like button  for users to be able to like post they fine interesting-->
<a  href="" data-href="{% url 'post:api_like' slug=post.slug %}">
<button id="like">like</button></a>
{% endfor %}

So you can see my like button id is not dynamic, which is one of the reasons I am facing this problem. How can I go about generating a dynamic button id for each like button in the for loop post?

Please Help me out

标签: javascriptpythondjangohtml

解决方案


HTML 中的标识符必须是唯一的 ,而不是分配一个 CSS 类,然后使用它来附加事件处理程序。

如果您想保留可以使用方法获取的任意数据,我建议您使用自定义属性,而不是使用id属性。data-*.data()

{% for post in allpost %} <!--for loop to get all post objects in data base-->

    <!-- like button  for users to be able to like post they fine interesting-->
    <button type="button" class="like" data-id="{{post.id}}">like</button>
{% endfor %}

这是一个附加事件处理程序并获取事件数据的 jQuery脚本click

$(function (){ 
    $('.like').on('click', function(){ 
        //Fetch Id 
        var id = $(this).data('id');                
    }); 
}); 

推荐阅读