View Code
(function ($) {
$.fn.menu = function (options) {
if (typeof options != 'undefined' && options.constructor === Array) options = { data: options };
var opts = $.extend({}, $.fn.menu.defaults, options);
var _tempMenuData = [];
//返回数据级别
function getLevel(id) {
var _level = 0;
var _o = getMenuData(id);
while (_o != null) {
_level ;
_o = getMenuData(_o.pid);
}
return _level;
}
//返回数据对象
function getMenuData(id) {
for (var i = 0; i < opts.data.length; i ) {
if (opts.data[i].id == id)
return opts.data[i];
}
return null;
}
//返回生成的HTML
function getHtml(pid) {
var _li_data = getData(pid);
if (_li_data.length == 0) return null;
var _ul = $('
');
$.each(_li_data, function (i, _d) {
var _children = getHtml(_d.id);
var _li = $('
').appendTo(_ul);
if (_d.n == null || _d.n.length == 0) {
_li.addClass('spacing');
} else if (typeof _d.fn === 'function') {
$('
').html(_d.n)
.click(function () {
_d.fn(_d.url);
}).appendTo(_li);
} else if (_d.url.length > 0) {
$('
').html(_d.n).appendTo(_li);
}
if (_children != null) {
_li.addClass('item-has-children');
_children.appendTo(_li);
_li.bind({
mouseover: function () {
_children.show();
},
mouseout: function () {
_children.hide();
}
});
}
})
if (pid == null && opts.type == 1) {
_ul.addClass('horizontal');
} else {
var _level = getLevel(pid);
_level > 0 && _ul.hide();
_ul.addClass('vertical');
if (_level > opts.type)
_ul.addClass('offset');
}
return _ul;
}
//返回下级数据数组
function getData(pid) {
var _data = [];
_tempMenuData = $.grep(_tempMenuData, function (_d) {
if (_d.pid == pid) {
_data.push(_d);
return true;
}
return false;
}, true);
return _data;
}
return this.each(function () {
var me = $(this);
me.addClass('ctcx-menu');
if (opts.data != null && opts.data.length > 0) {
$.merge(_tempMenuData, opts.data);
me.append(getHtml(null));
}else {
. ;
_ul.hide();
self.bind({
mouseover: function () {
_ul.show();
_ul.hide(); } ); $.fn.menu.defaults = {
type: 1, //The display mode of the menu (mainly refers to whether the first level is horizontal or vertical, the default is horizontal 1, vertical 0)
/*
data : Dynamically generate array data for the menu. If this data is specified, the menu will be filled with this data (the original data in the menu is replaced)
Data format: [menu,menu,...]
Menu object format: { id: 1, pid: null, n: 'Menu name 1', url: '#', fn: callback function}
*/
);
Call JS code
Copy code
The code is as follows:
View Code
$(function () {
var _menuData = [
. '#' },
{ id: 4, pid: null, n: 'Menu name 4', url: '#' },
{ id: 5, pid: null, n: 'Menu name 5' ', url: '#' },
'Menu name 7', url: '#' },
3, n: 'Menu name 9', url: '#' },
11, pid: 9, n: 'Menu name 11', url: '#' },
> }. : 0, data: _menuData });
🎜>
HTML
Copy code
The code is as follows:
View Code
여기를 클릭
하여 사용 예시와 모든 파일을 다운로드하세요.