自己尝试封装的一个在工作当中使用的多级弹窗插件:
;(function ($, window, document) { //用一个自调用匿名函数把插架代码包裹起来,防止代码污染
$.fn.multi = function (options, callback) {
let defaults = { //defaults 使我们设置的默认参数。
trigger: '', //触发事件的class
popClass1: '', //第一个弹窗的class
popClass2: '', //第二个弹窗的class
};
options = $.extend(defaults, options); //将传入参数和默认参数合并
let $this = $(this); //响应事件对象
//触发弹窗
$this.on('click', options.trigger, function () { //功能代码部分,绑定事件
//关闭页面上的弹窗
$(options.popClass1).parent().hide();
$(options.popClass2).parent().hide();
//打开新触发的弹窗
$(this).next().show();
});
let levelValue = ''; //每层选择的值
//第一层 事件代理
$this.on('click', options.popClass1 + ">li", function () {
//控制背景颜色高亮
$(this).addClass("active").siblings().removeClass("active");
// 获取当前点击的li的子元素的HTML节点 将获取的节点放到页面显示的第二级中
let html = $(this).children("ul").html();
$(this).parent().parent().next().children(".multi-level-ul2").html(html);
$(this).parent().parent().next().show();
});
//第二层 事件代理
$this.on('click', options.popClass2 + ">li", function () {
$(this).addClass("active").siblings().removeClass("active");
levelValue = $(this).children("span").text();
$(this).parent().parent().prev().prev().text(levelValue);
let level = $this.attr('data-level');
//把选择的值和层级通过回调函数传递回去
callback(levelValue, level);
$(this).parent().parent().prev().hide();
$(this).parent().parent().hide();
});
//点击空白处隐藏div
$(document).click(function (event) {
let targetArea = $('.multi-level-wrap'); // 设置目标区域
if (!targetArea.is(event.target) && targetArea.has(event.target).length === 0) {
$(options.popClass1).parent().hide();
$(options.popClass2).parent().hide();
}
});
}
})(jQuery, window, document);
在页面当中调用:
$('.multi-level-wrap').each(function() {
$(this).multi({
trigger: '.multi-level-input', //触发事件的class
popClass1: '.multi-level-ul1', //第一个弹窗的class
popClass2: '.multi-level-ul2', //第二个弹窗的class
}, function(params, level) {
})
})
参考链接: https://blog.csdn.net/weixin_39398244/article/details/81539486