bootstrap3中Select树的实现

为了项目需要写了一个select树的实现,虽然写的比较挫,见谅。还有一些功能还没实现。效果如图:

bootstrap3中Select树的实现_第1张图片

!function($) {

	var SelectTree = function(element, options) {
		this.element = element;
		this.options = options;
		this.init(options);
	}
	SelectTree.prototype = {
		convert : function(rows) {
			var element = $(this.element);
			element.empty();
			var options  = this.options;
			function exists(rows, master) {
				for (var i = 0; i < rows.length; i++) {
					if (rows[i].id == master)
						return true;
				}
				return false;
			}
			var nodes = [];
			for (var i = 0; i < rows.length; i++) {
				var row = rows[i];
				if (!exists(rows, row[options.pid])) {
					nodes.push({
						id : row[options.id],
						text : ''
					});
					element.append("<option ' id=" + row[options.id] + ">" + row[options.value]+ "</option>");
				}
			}
			while (nodes.length) {
				var node = nodes.shift();
				for (var i = 0; i < rows.length; i++) {
					var row = rows[i];
					if (row.master == node.id) {
						nodes.push({
							id : row[options.id],
							text : node.text + options.spik
						});
						element.find("#"+row[options.pid]).after("<option id="+ row[options.id]+">" + node.text + options.spik + row[options.value] + "</option>");
					}
				}
			}
			return nodes;
		},
		init : function(options) {
			var _this = this;
			if (options.url) {
				$.ajax({
					type : options.method,
					url : options.url,
					data : options.params,
					dataType : 'json',
					cache : options.cache
				}).done(function(data) {
					try {
						// 获得root对象
						var items = data;
						if ($.isArray(data[options.root])) {
							items = data[opts.root];
						}
						var row =items;
						row = _this.convert(row);
					} catch (e) {
						throw e;
					}

				});
			} else {
				var items = options.data || {};
				_this.convert(row);
			}
		}
	}
	$.fn.selectTree = function(options, param) {
		if (typeof options == 'string') {
			return $.fn.selectTree.methods[options](this, param);
		} else {
			var data = this.data('SelectTree');
			if (!data) {
				var options = $.extend(true, {}, $.fn.selectTree.defaults,
						options);
				data = new SelectTree(this, options);
			} else {
				data.opts = $.extend(true, {}, data.opts, options);
			}

			this.data('selectTree', data);
			return $.extend(true, this, data);
		}
	};
	$.fn.selectTree.methods = {
		options : function(jq) {

		},
		add : function(jq, options) {
			return jq.each(function() {

			});
		}
	};
	$.fn.selectTree.defaults = {
		url : ‘’,//url地址
		data : null,//如果是本地的数据
		params : {},//提交后台的数据
		method : 'POST',
		root : 'root',
		id : 'id',//id号
		spik:'--',//
		value : 'title',
		pid : 'master',//父id
		cache : false,
		loadFilter : function(d) {
			return d;
		}
	};
}(window.jQuery);


你可能感兴趣的:(bootstrap3中Select树的实现)