使用JQuery为新添加按钮绑定点击事件,解决弹窗批量隐藏问题
解决点击关闭按钮批量隐藏提示框的问题
问题根源
你当前代码里的$("#mainBodyContainer").append()返回的是容器本身(即#mainBodyContainer),不是刚创建的单个提示框元素。所以每次调用newAlert.find(".alert-del")都会选中容器内所有的关闭按钮,点击时自然会批量隐藏所有提示框。
修复方案
这里提供三种可行的修改方式,按需选择:
方式1:先创建元素再追加(清晰直观)
先单独创建新提示框元素,拿到它的引用后再追加到容器,这样能精准操作当前新创建的提示框:
// 先创建新的alert元素 const newAlert = $(` <div class="alert alert-info shadow-lg p-2 mt-2"> <p> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current flex-shrink-0 w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path> </svg> <span>a</span> </p> <strong class="text-xl align-center cursor-pointer alert-del">×</strong> </div> `); // 将新元素追加到容器 $("#mainBodyContainer").append(newAlert); // 给当前新提示框的关闭按钮绑定事件 const deleteAlertButton = newAlert.find(".alert-del") deleteAlertButton.on("click", () => { newAlert.addClass("hidden"); // 直接操作新创建的alert元素 });
方式2:用this指代当前点击的按钮
使用普通函数而非箭头函数(箭头函数没有自己的this),让this指向被点击的关闭按钮,再找到它的父提示框:
$("#mainBodyContainer").append(` <div class="alert alert-info shadow-lg p-2 mt-2"> <p> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current flex-shrink-0 w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path> </svg> <span>a</span> </p> <strong class="text-xl align-center cursor-pointer alert-del">×</strong> </div> `); // 给最新的关闭按钮绑定事件,用this定位当前按钮 $(".alert-del").last().on("click", function() { $(this).parent().addClass("hidden"); });
方式3:事件委托(推荐多次创建提示框的场景)
只需要在页面初始化时给容器绑定一次事件,就能自动处理后续动态生成的所有提示框关闭逻辑,无需每次创建都绑定事件:
// 页面初始化时绑定一次事件委托 $("#mainBodyContainer").on("click", ".alert-del", function() { $(this).parent().addClass("hidden"); }); // 后续每次创建提示框只需追加即可 const newAlert = $(` <div class="alert alert-info shadow-lg p-2 mt-2"> <p> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current flex-shrink-0 w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path> </svg> <span>a</span> </p> <strong class="text-xl align-center cursor-pointer alert-del">×</strong> </div> `); $("#mainBodyContainer").append(newAlert);
内容的提问来源于stack exchange,提问作者Teyrox
相关产品推荐
相关产品推荐

