javascript - 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
解决方案
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');
});
});
推荐阅读
- jquery - 单击按钮后,如何在 Botostrap DateTimePicker 中为日期添加月份?
- swift - Swift // 多个列表单元格中的相同图像更改(每 4 个单元格)
- python-3.x - 将统一值传递给顶点和片段着色器
- etl - Xero 到 DataFactory 设置
- firefox - WebDriverException:无法解码来自木偶的响应
- android - 如何防止从控制台删除数据库?
- linux - find - 我需要从 RPM 列表中获取包的名称
- ag-grid - 基于数据值的 AG-grid 十进制精度
- sql-server - 跨服务器查询
- ruby - 如何使用 Ruby 元编程动态创建具有初始化方法的类?