如何将jQuery绑定的Bootstrap Notify点击逻辑改为可调用JS函数
改造实现代码
你可以直接复用原有逻辑的配置,将动态参数抽为函数入参即可,以下是可直接使用的完整实现:
// 通知触发函数,msg为必填的通知内容参数,支持传入第二个参数自定义配置 function showNotification(msg, customConfig = {}) { // 基础默认配置,和原有逻辑保持一致,可根据需求自行修改默认值 const defaultConfig = { from: 'top', align: 'left', type: 'primary', title: 'Bootstrap Notify', showProgressbar: false }; // 合并用户自定义配置和默认配置,自定义参数优先级更高 const finalConfig = Object.assign({}, defaultConfig, customConfig); $.notify({ title: finalConfig.title, message: msg, target: "_blank" }, { element: "body", position: null, type: finalConfig.type, allow_dismiss: true, newest_on_top: false, showProgressbar: finalConfig.showProgressbar, placement: { from: finalConfig.from, align: finalConfig.align }, offset: 20, spacing: 10, z_index: 1031, delay: 4000, timer: 2000, url_target: "_blank", mouse_over: null, animate: { enter: "animated fadeInDown", exit: "animated fadeOutUp" }, onShow: null, onShown: null, onClose: null, onClosed: null, icon_type: "class", template: '<div data-notify="container" class="col-11 col-sm-3 alert alert-{0} " role="alert"><button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button><span data-notify="icon"></span> <span data-notify="title">{1}</span> <span data-notify="message">{2}</span><div class="progress" data-notify="progressbar"><div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div><a href="{3}" target="{4}" data-notify="url"></a></div>' }) } // 原有按钮的点击事件可修改为调用上述函数,保持原有功能正常运行 $("body").on("click", ".notify-btn", function (e) { e.preventDefault(); showNotification("Here is a notification!", { from: $(this).data("from"), align: $(this).data("align") }) })
使用示例
- 基础调用,仅传入通知内容:
showNotification("操作执行成功") - 自定义参数调用,可修改通知位置、类型、标题等属性:
showNotification("提交失败,请检查输入内容", { from: "bottom", align: "right", type: "danger", title: "错误提示" })
内容的提问来源于stack exchange,提问作者Manoranjan Jena
相关产品推荐
相关产品推荐

