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

同ID不同属性按钮点击异常:Django场景下的解决需求

解决Django循环生成按钮仅第一个触发事件的问题

问题根源

HTML规范中ID属性必须唯一,document.getElementById()方法只会返回DOM中第一个匹配该ID的元素。你循环生成的所有按钮都使用了相同的NotifyBtn ID,导致只有第一个按钮绑定了点击事件,其余按钮没有任何事件监听。

另外,你的Django模板代码存在语法错误:name="person.FName"和town="person.LName"会被渲染成字符串字面量,而不是实际的用户数据,需要改成模板变量语法{{ person.FName }}和{{ person.LName }}。

解决方案

方案1:使用类选择器批量绑定事件

修改模板,将重复的ID改为类名,并修正模板变量:

{% for person in page_obj %}
    <button class="NotifyBtn" name="{{ person.FName }}" town="{{ person.LName }}">Press Me</button>
{% endfor %}

修改JavaScript代码,通过类选择器获取所有按钮,逐个绑定点击事件:

// 获取所有带NotifyBtn类的按钮,遍历绑定事件
document.querySelectorAll('.NotifyBtn').forEach(button => {
    button.addEventListener('click', function() {
        const name = this.getAttribute('name');
        const town = this.getAttribute('town');
        
        fetch("{% url 'alert_via_JSON_Response' %}", {
            method: "POST",
            headers: {
                "X-CSRFToken": "{{ csrf_token }}",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ 
                message: `Hi there: ${name} born in ${town}`
            })
        })
        .then(response => response.json())
        .then(data => alert(data.status));
    });
});

方案2:事件委托(推荐用于动态生成元素)

如果按钮是动态生成的(比如分页加载新增),事件委托更高效——给父容器绑定一次事件,利用事件冒泡处理子元素的点击:

先给按钮添加父容器:

<div class="button-group">
{% for person in page_obj %}
    <button class="NotifyBtn" name="{{ person.FName }}" town="{{ person.LName }}">Press Me</button>
{% endfor %}
</div>

JavaScript代码:

// 给父容器绑定事件,通过事件目标判断是否点击了目标按钮
document.querySelector('.button-group').addEventListener('click', function(e) {
    if (e.target.classList.contains('NotifyBtn')) {
        const name = e.target.getAttribute('name');
        const town = e.target.getAttribute('town');
        
        fetch("{% url 'alert_via_JSON_Response' %}", {
            method: "POST",
            headers: {
                "X-CSRFToken": "{{ csrf_token }}",
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ 
                message: `Hi there: ${name} born in ${town}`
            })
        })
        .then(response => response.json())
        .then(data => alert(data.status));
    }
});

后端代码说明

你的Django视图函数无需修改,已经能正确处理POST请求并返回JSON响应。

内容的提问来源于stack exchange,提问作者Jose Serra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:27:24