社交媒体网站Flash消息关闭异常:仅首个按钮生效,求解决方法
问题:多条Flash消息仅第一条可关闭
我正在开发一个社交媒体网站,当页面弹出两条Flash消息时,关闭按钮仅对第一条消息生效——点击可正常关闭该消息,但点击第二条消息的关闭按钮完全没有反应。以下是我的代码,恳请帮忙分析原因并提供修复方案,谢谢。
CSS代码
.hide { display: none; } .alerts { z-index: 1; position: fixed; display: flex; flex-direction: column; width: calc(100% - 3rem); max-width: 1000px; left: 50%; transform: translateX(-50%); } .alert { z-index: 1; color: white; margin: .5rem 0px; margin-top: 1rem; padding: 1.5rem; border-radius: 3px; box-shadow: 0px 5px 15px -2px rgba($color: #000000, $alpha: .6); backdrop-filter: blur(1px); width: 100%; text-transform: uppercase; justify-content: space-between; &-success { background-color: rgba(81, 158, 81, 0.8); } &-error { background-color: rgba(238, 67, 67, 0.8); } &-info { background-color: rgba(87, 152, 243, 0.6); } }
HTML代码
<div class="alerts"> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }} flex flex-ai-c"> <span>{{ message }}</span> <button id="close-alert" class="btn-close"></button> </div> {% endfor %} {% endif %} {% endwith %} </div>
JS代码
$(function () { $("#close-alert").on("click", function () { $("#close-alert").parent().addClass("hide"); }); });
问题原因
- ID唯一性违规:HTML规范要求
id属性必须全局唯一,但你通过循环给每个关闭按钮都设置了id="close-alert",浏览器只会识别第一个拥有该ID的元素,后续按钮无法绑定点击事件。 - 目标元素错误:JS中用
$("#close-alert")选择元素时,仅会匹配第一个按钮;修改父元素时,$("#close-alert").parent()也只会指向第一个按钮的父容器,无法对应当前点击的消息框。
修复方案
步骤1:修改HTML,替换ID为类
将按钮的id="close-alert"改为类名,保证元素标识的唯一性:
<div class="alerts"> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} <div class="alert alert-{{ category }} flex flex-ai-c"> <span>{{ message }}</span> <button class="btn-close close-alert"></button> </div> {% endfor %} {% endif %} {% endwith %} </div>
步骤2:修改JS,使用类选择器并绑定正确目标
用类选择器绑定事件,通过$(this)获取当前点击的按钮,再定位到它的父容器添加隐藏类:
$(function () { $(".close-alert").on("click", function () { $(this).parent().addClass("hide"); }); });
可选优化:直接移除消息元素
如果关闭后不需要保留消息的DOM结构,可以直接移除元素代替添加隐藏类:
$(function () { $(".close-alert").on("click", function () { $(this).parent().remove(); }); });
内容的提问来源于stack exchange,提问作者MrHeinzBeans
相关产品推荐
相关产品推荐

