如何单独关闭单个Toastr消息而非全部消息
解决Toastr单条消息关闭问题
你的问题核心是toastr.remove()默认会清除所有已显示的toast消息,要实现单条消息独立关闭,需要针对具体的toast实例进行操作,以下是修改方案:
解决方案步骤
- 保存toast实例引用:调用
toastr.warning()(或其他类型方法)时,会返回当前toast的DOM元素,将其保存为变量。 - 避免内联onclick:通过事件绑定的方式给按钮添加点击逻辑,确保能精准定位到当前按钮所属的toast容器。
- 精准移除单条toast:在按钮点击事件中,调用
toastr.remove()并传入当前toast实例,仅关闭该条消息。
修改后的完整代码
jQuery版本
chat.client.addNewNotificationToPage = function (name, message) { console.log("this is meeeeee"); toastr.options = { "closeButton": true, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-top-right", "preventDuplicates": false, "showDuration": "300", "hideDuration": "1000", "timeOut": 0, "extendedTimeOut": 0, "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut", "tapToDismiss": false }; // 构造消息内容,移除内联onclick,改用类名标识按钮 let notificationMessage = `${name} Has Order Number ${message} been picked up?<br /><button type="button" class="btn clear btn-yes">Yes</button><button type="button" class="btn clear btn-no">No</button>`; // 创建toast并保存实例 const toastInstance = toastr["warning"](notificationMessage, "We've Noticed This Hasn't Been Updated"); // 绑定Yes按钮点击事件:关闭当前toast $(toastInstance).find(".btn-yes").on("click", function() { toastr.remove(toastInstance); }); // 绑定No按钮点击事件:跳转页面 $(toastInstance).find(".btn-no").on("click", function() { window.location.href = 'https://randomsite.com'; }); };
原生JS版本(无需jQuery)
chat.client.addNewNotificationToPage = function (name, message) { console.log("this is meeeeee"); toastr.options = { "closeButton": true, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-top-right", "preventDuplicates": false, "showDuration": "300", "hideDuration": "1000", "timeOut": 0, "extendedTimeOut": 0, "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut", "tapToDismiss": false }; let notificationMessage = `${name} Has Order Number ${message} been picked up?<br /><button type="button" class="btn clear btn-yes">Yes</button><button type="button" class="btn clear btn-no">No</button>`; const toastInstance = toastr["warning"](notificationMessage, "We've Noticed This Hasn't Been Updated"); // 绑定Yes按钮事件 const yesBtn = toastInstance.querySelector(".btn-yes"); yesBtn.addEventListener("click", function() { toastr.remove(toastInstance); }); // 绑定No按钮事件 const noBtn = toastInstance.querySelector(".btn-no"); noBtn.addEventListener("click", function() { window.location.href = 'https://randomsite.com'; }); };
关键说明
toastr.warning()返回的toastInstance是当前这条toast的DOM元素,通过它可以精准操作该消息的内部元素。- 事件绑定方式替代内联
onclick,避免了全局上下文的混淆,确保点击操作只作用于当前toast。 - 调用
toastr.remove(toastInstance)时,只会移除指定的toast实例,不会影响其他已显示的消息。
内容的提问来源于stack exchange,提问作者Jacob Kresak
相关产品推荐
相关产品推荐

