You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Django展示的每篇帖子添加JavaScript更新按钮

解决Django帖子列表更新按钮重复添加的问题

问题根源

模板循环生成帖子时使用了重复的id="posts-div",而document.getElementById只会获取DOM中第一个匹配该ID的元素,导致所有更新按钮都被添加到第一篇帖子里。

修复步骤

1. 修改Django模板,给每个帖子容器设置唯一标识

把循环里的帖子div的id改成包含post.id的唯一值,同时将重复的id="user"改为class(HTML中id不能重复使用):

<div id="formulario" class="form-style" style="border: 5px solid rgb(255, 170, 0);">
    <h1>User's Posts</h1>
    {% for post in object_list %}
    <!-- 用post.id生成唯一ID,确保每个帖子容器都有独立标识 -->
    <div id="post-{{ post.id }}" class="posts-div" style="border: 5px solid red;">
        <h3 class="user">{{ post.usuario }} - User with id: {{ post.id }}</h3>
        <h3>{{ post.contenido }} - {{ post.id }}</h3>
    </div>
    {% endfor %}
    <h1>Agregar</h1>
    <form method="post">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Save">
    </form>
</div>

2. 更新JavaScript代码,匹配对应帖子容器添加按钮

遍历API返回的帖子数据时,根据post.id找到对应的容器,再为其添加更新按钮:

addEventListener('DOMContentLoaded', (event) => {     
    fetch('/api/posts')
    .then(response => response.json())
    .then(data => {
        data.forEach(post => {
            // 通过唯一ID定位当前帖子的容器
            const postDiv = document.getElementById(`post-${post.id}`); 
            if (postDiv) {
                const updateBtn = document.createElement('button');
                updateBtn.textContent = 'Update';
                // 提前绑定点击事件,后续可扩展更新逻辑
                updateBtn.addEventListener('click', () => {
                    console.log(`准备更新ID为${post.id}的帖子`);
                    // 这里可以添加Fetch PUT请求的逻辑,比如弹出编辑表单
                });
                postDiv.appendChild(updateBtn);
            }
        });
    });
});

额外说明

如果不想用唯一ID,也可以给所有帖子容器加统一的class(比如class="posts-div"),然后通过索引匹配API返回的数据和DOM元素,但这种方式依赖数据顺序与DOM渲染顺序完全一致,可靠性不如唯一ID方案。

内容的提问来源于stack exchange,提问作者Rodolfo Schiavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:25:23