後臺管理頁面通過點擊左側導航欄的菜單項實現右邊內容的改變

前端頁面部分

<aside id="left-panel">
	<!-- User info -->
	<div class="login-info">
		<span> 
			<a href="javascript:void(0);" id="show-shortcut"
			data-action="toggleShortcut"> <img
				src="${ctx}/img/avatars/sunny.png" alt="me" class="online" /> <span>
					john.doe
			</span> <i class="fa fa-angle-down"></i>
		</a>
		</span>
	</div>
	<!-- 導航欄-->
	<nav>
	<ul>
			<li class=""><a href="${ctx}/manage/businessManag.html" title="商家管理"><i class="fa fa-lg fa-fw fa-home"></i> <span class="menu-item-parent">商家管理</span></a>
				<ul>
					<li class="">
					<a href="${ctx}/manage/businessManag.html" title="商家管理"><span class="menu-item-parent">商家管理</span></a>
					</li>
					<li class="">
						<a href="${ctx}/manage/mealsManag.html" title="菜品管理"><span class="menu-item-parent">菜品管理</span></a>
					</li>
					<li class="">
						<a href="${ctx}/manage/orderManag.html" title="訂單管理"><span class="menu-item-parent">訂單管理</span></a>
					</li>
					<li class="">
						<a href="${ctx}/manage/userManag.html" title="用戶管理"><span class="menu-item-parent">用戶管理</span></a>
					</li>
					<li class="">
						<a href="${ctx}/manage/testManager.html" title="測試頁面"><span class="menu-item-parent">測試頁面</span></a>
					</li>
				</ul>
			</li>
		</ul>
	</nav>
	<span  class="minifyme" data-action="minifyMenu"> 
		<i	class="fa fa-arrow-circle-left hit"></i>
	</span>

</aside>

<!-- #MAIN PANEL 切換內容的主窗口-->
<div id="main" role="main">
	<div id="ribbon">
		<span class="ribbon-button-alignment"> <span id="refresh"
			class="btn btn-ribbon" data-action="resetWidgets"
			data-title="refresh" rel="tooltip" data-placement="bottom"
			data-original-title="<i class='text-warning fa fa-warning'></i> Warning! This will reset all your widget settings."
			data-html="true"
			data-reset-msg="Would you like to RESET all your saved widgets and clear LocalStorage?"><i
				class="fa fa-refresh"></i></span>
		</span>

		<!-- breadcrumb -->
		<ol class="breadcrumb">
			<!-- This is auto generated -->
		</ol>
		<!-- end breadcrumb -->

	</div>

	<!-- #MAIN CONTENT -->
	<div id="content"></div>

	<!-- END #MAIN CONTENT -->

</div>
<!-- END #MAIN PANEL -->

<!-- #PAGE FOOTER -->
<div class="page-footer">
	<div class="row">
		<div class="col-xs-12 col-sm-6">
		</div>

		<div class="col-xs-6 col-sm-6 text-right hidden-xs">
			<div class="txt-color-white inline-block">
			</div>
			<!-- end div-->
		</div>
		<!-- end col -->
	</div>
	<!-- end row -->
</div>
<!-- END FOOTER -->

js代碼部分

變量值如下:

$.root_ = $('body');	
$.navAsAjax = true; 
debugState = true,
bread_crumb = $('#ribbon ol.breadcrumb'),

左側導航欄組菜單項的打開與關閉

$.fn.extend({

	//pass the options variable to the function
	jarvismenu : function(options) {

		var defaults = {
			accordion : 'true',
			speed : 200,
			closedSign : '[+]',
			openedSign : '[-]'
		},

		// Extend our default options with those provided.
			opts = $.extend(defaults, options),
		//Assign current element to variable, in this case is UL element
			$this = $(this);

		//add a mark [+] to a multilevel menu
		$this.find("li").each(function() {
			if ($(this).find("ul").size() !== 0) {
				//add the multilevel sign next to the link
				$(this).find("a:first").append("<b class='collapse-sign'>" + opts.closedSign + "</b>");

				//avoid jumping to the top of the page when the href is an #
				if ($(this).find("a:first").attr('href') == "#") {
					$(this).find("a:first").click(function() {
						return false;
					});
				}
			}
		});

		//open active level
		$this.find("li.active").each(function() {
			$(this).parents("ul").slideDown(opts.speed);
			$(this).parents("ul").parent("li").find("b:first").html(opts.openedSign);
			$(this).parents("ul").parent("li").addClass("open");
		});

		$this.find("li a").click(function() {

			if ($(this).parent().find("ul").size() !== 0) {

				if (opts.accordion) {
					//Do nothing when the list is open
					if (!$(this).parent().find("ul").is(':visible')) {
						parents = $(this).parent().parents("ul");
						visible = $this.find("ul:visible");
						visible.each(function(visibleIndex) {
							var close = true;
							parents.each(function(parentIndex) {
								if (parents[parentIndex] == visible[visibleIndex]) {
									close = false;
									return false;
								}
							});
							if (close) {
								if ($(this).parent().find("ul") != visible[visibleIndex]) {
									$(visible[visibleIndex]).slideUp(opts.speed, function() {
										$(this).parent("li").find("b:first").html(opts.closedSign);
										$(this).parent("li").removeClass("open");
									});

								}
							}
						});
					}
				}// end if
				if ($(this).parent().find("ul:first").is(":visible") && !$(this).parent().find("ul:first").hasClass("active")) {
					$(this).parent().find("ul:first").slideUp(opts.speed, function() {
						$(this).parent("li").removeClass("open");
						$(this).parent("li").find("b:first").delay(opts.speed).html(opts.closedSign);
					});

				} else {
					$(this).parent().find("ul:first").slideDown(opts.speed, function() {
						/*$(this).effect("highlight", {color : '#616161'}, 500); - disabled due to CPU clocking on phones*/
						$(this).parent("li").addClass("open");
						$(this).parent("li").find("b:first").delay(opts.speed).html(opts.openedSign);
					});
				} // end else
			} // end if
		});
	} // end function
});

url地址跳轉

首先我們需要了解window.location對象所包含的屬性

屬性 描述
hash 從井號 (#) 開始的 URL(錨),返回值包含#
hostname 當前 URL 的主機名
port 當前 URL 的端口號
host 主機名和當前 URL 的端口號
href 完整的URL
pathname 當前 URL的路徑和文件名
protocol 當前 URL使用的協議
search 從問號 (?) 開始的 URL(查詢部分)

由以上知識可以寫出url跳轉部分的代碼:

//先判斷導航欄裏是否有內容
if ($('nav').length) {
	checkURL();
}
//菜單項點擊事件
$(document).on('click', 'nav a[href!="#"]', function(e) {

	e.preventDefault();
	var $this = $(e.currentTarget);

	//判斷a的父標籤li標籤是否被選中以及a標籤是否有target屬性
	if (!$this.parent().hasClass("active") && !$this.attr('target')) {

		// update window with hash
		// you could also do here:  thisDevice === "mobile" - and save a little more memory

		if ($.root_.hasClass('mobile-view-activated')) {

			$.root_.removeClass('hidden-menu');
			$('html').removeClass("hidden-menu-mobile-lock");
			window.setTimeout(function() {
				//忽略地址欄的請求參數
				if (window.location.search) {
					window.location.href =
						window.location.href.replace(window.location.search, '')
							.replace(window.location.hash, '') + '#' + $this.attr('href');
				} else {
					window.location.hash = $this.attr('href');
				}
			}, 150);
			// it may not need this delay...
		} else {
			if (window.location.search) {
				window.location.href =
					window.location.href.replace(window.location.search, '')
						.replace(window.location.hash, '') + '#' + $this.attr('href');
			} else {
				window.location.hash = $this.attr('href');
			}
		}
	}
});

// fire links with targets on different window
$(document).on('click', 'nav a[target="_blank"]', function(e) {
	e.preventDefault();
	var $this = $(e.currentTarget);

	window.open($this.attr('href'));
});

// fire links with targets on same window
$(document).on('click', 'nav a[target="_top"]', function(e) {
	e.preventDefault();
	var $this = $(e.currentTarget);

	window.location = ($this.attr('href'));
});

// all links with hash tags are ignored
$(document).on('click', 'nav a[href="#"]', function(e) {
	e.preventDefault();
});

// DO on hash change
$(window).on('hashchange', function() {
	checkURL();
});
	

地址欄url地址處理

function checkURL() {

	//取出從#開始的url(錨),不包含#
	var url = location.href.split('#').splice(1).join('');
	//BEGIN: IE11解決方案
	if (!url) {
		try {
			var documentUrl = window.document.URL;
			if (documentUrl) {
				if (documentUrl.indexOf('#', 0) > 0 && documentUrl.indexOf('#', 0) < (documentUrl.length + 1)) {
					url = documentUrl.substring(documentUrl.indexOf('#', 0) + 1);
				}
			}
		} catch (err) {}
	}
	//END: IE11解決方案

	container = $('#content');
	// Do this if url exists (for page refresh, etc...)
	if (url) {
		// remove all active class
		$('nav li.active').removeClass("active");
		// match the url and add the active class
		$('nav li:has(a[href="' + url + '"])').addClass("active");
		var title = ($('nav a[href="' + url + '"]').attr('title'));

		// change page title from global var
		document.title = (title || document.title);
		
		// debugState
		if (debugState){
			root.console.log("Page title: %c " + document.title, debugStyle_green);
		}
		
		// parse url to jquery
		loadURL(url + location.search, container);

	} else {

		// grab the first URL from nav
		var $this = $('nav > ul > li:first-child > a[href!="#"]');

		//update hash
		window.location.hash = $this.attr('href');
		
		//clear dom reference
		$this = null;

	}

}

ajax實現右邊頁面內容變換

function loadURL(url, container) {

	// debugState
	if (debugState){
		root.root.console.log("Loading URL: %c" + url, debugStyle);
	}

	$.ajax({
		type : "GET",
		url : url,
		dataType : 'html',
		cache : true, // (warning: setting it to false will cause a timestamp and will call the request twice)
		beforeSend : function() {
			//IE11 bug fix for googlemaps (delete all google map instances)
			//check if the page is ajax = true, has google map class and the container is #content
			if ($.navAsAjax && $(".google_maps")[0] && (container[0] == $("#content")[0]) ) {

				// target gmaps if any on page
				var collection = $(".google_maps"),
					i = 0;
				// run for each	map
				collection.each(function() {
					i ++;
					// get map id from class elements
					var divDealerMap = document.getElementById(this.id);
					
					if(i == collection.length + 1) {
						// "callback"
					} else {
						// destroy every map found
						if (divDealerMap) divDealerMap.parentNode.removeChild(divDealerMap);

						// debugState
						if (debugState){
							root.console.log("Destroying maps.........%c" + this.id, debugStyle_warning);
						}
					}
				});

				// debugState
				if (debugState){
					root.console.log("✔ Google map instances nuked!!!");
				}
				
			} //end fix
			
			// destroy all datatable instances
			if ( $.navAsAjax && $('.dataTables_wrapper')[0] && (container[0] == $("#content")[0]) ) {
				
				var tables = $.fn.dataTable.fnTables(true);				
				$(tables).each(function () {
					
					if($(this).find('.details-control').length != 0) {
						$(this).find('*').addBack().off().remove();
						$(this).dataTable().fnDestroy();
					} else {
						$(this).dataTable().fnDestroy();
					}
					
				});
				
				// debugState
				if (debugState){
					root.console.log("✔ Datatable instances nuked!!!");
				}
			}
			// end destroy
			
			// pop intervals (destroys jarviswidget related intervals)
			if ( $.navAsAjax && $.intervalArr.length > 0 && (container[0] == $("#content")[0]) && enableJarvisWidgets ) {
				
				while($.intervalArr.length > 0)
					clearInterval($.intervalArr.pop());
					// debugState
					if (debugState){
						root.console.log("✔ All JarvisWidget intervals cleared");
					}
					
			}
			// end pop intervals
			
			// destroy all widget instances
			if ( $.navAsAjax && (container[0] == $("#content")[0]) && enableJarvisWidgets && $("#widget-grid")[0] ) {
				
				$("#widget-grid").jarvisWidgets('destroy');
				// debugState
				if (debugState){
					root.console.log("✔ JarvisWidgets destroyed");
				} 
				
			}
			// end destroy all widgets 
			
			// cluster destroy: destroy other instances that could be on the page 
			// this runs a script in the current loaded page before fetching the new page
			if ( $.navAsAjax && (container[0] == $("#content")[0]) ) {

				/*
				 * The following elements should be removed, if they have been created:
				 *
				 *	colorList
				 *	icon
				 *	picker
				 *	inline
				 *	And unbind events from elements:
				 *	
				 *	icon
				 *	picker
				 *	inline
				 *	especially $(document).on('mousedown')
				 *	It will be much easier to add namespace to plugin events and then unbind using selected namespace.
				 *	
				 *	See also:
				 *	
				 *	http://f6design.com/journal/2012/05/06/a-jquery-plugin-boilerplate/
				 *	http://keith-wood.name/pluginFramework.html
				 */
				
				// this function is below the pagefunction for all pages that has instances

				if (typeof pagedestroy == 'function') { 

				  try {
						pagedestroy(); 

						if (debugState){
							root.console.log("✔ Pagedestroy()");
					   } 
					}
					catch(err) {
					   pagedestroy = undefined; 

					   if (debugState){
							root.console.log("! Pagedestroy() Catch Error");
					   } 
				  }

				} 

				// destroy all inline charts
				
				if ( $.fn.sparkline && $("#content .sparkline")[0] ) {
					$("#content .sparkline").sparkline( 'destroy' );
					
					if (debugState){
						root.console.log("✔ Sparkline Charts destroyed!");
					} 
				}
				
				if ( $.fn.easyPieChart && $("#content .easy-pie-chart")[0] ) {
					$("#content .easy-pie-chart").easyPieChart( 'destroy' );
					
					if (debugState){
						root.console.log("✔ EasyPieChart Charts destroyed!");
					} 
				}

				

				// end destory all inline charts
				
				// destroy form controls: Datepicker, select2, autocomplete, mask, bootstrap slider
				
				if ( $.fn.select2 && $("#content select.select2")[0] ) {
					$("#content select.select2").select2('destroy');
					
					if (debugState){
						root.console.log("✔ Select2 destroyed!");
					}
				}
				
				if ( $.fn.mask && $('#content [data-mask]')[0] ) {
					$('#content [data-mask]').unmask();
					
					if (debugState){
						root.console.log("✔ Input Mask destroyed!");
					}
				}
				
				if ( $.fn.datepicker && $('#content .datepicker')[0] ) {
					$('#content .datepicker').off();
					$('#content .datepicker').remove();
					
					if (debugState){
						root.console.log("✔ Datepicker destroyed!");
					}
				}
				
				if ( $.fn.slider && $('#content .slider')[0] ) {
					$('#content .slider').off();
					$('#content .slider').remove();
					
					if (debugState){
						root.console.log("✔ Bootstrap Slider destroyed!");
					}
				}
							
				// end destroy form controls
				
				
			}
			// end cluster destroy
			
			// empty container and var to start garbage collection (frees memory)
			pagefunction = null;
			container.removeData().html("");
			
			// place cog
			container.html('<h1 class="ajax-loading-animation"><i class="fa fa-cog fa-spin"></i> Loading...</h1>');
		
			// Only draw breadcrumb if it is main content material
			if (container[0] == $("#content")[0]) {
				
				// clear everything else except these key DOM elements
				// we do this because sometime plugins will leave dynamic elements behind
				$('body').find('> *').filter(':not(' + ignore_key_elms + ')').empty().remove();
				
				// draw breadcrumb
				drawBreadCrumb();
				
				// scroll up
				$("html").animate({
					scrollTop : 0
				}, "fast");
			} 
			// end if
		},
		success : function(data) {
			
			// dump data to container
			container.css({
				opacity : '0.0'
			}).html(data).delay(50).animate({
				opacity : '1.0'
			}, 300);
			
			// clear data var
			data = null;
			container = null;
		},
		error : function(xhr, status, thrownError, error) {
			container.html('<h4 class="ajax-loading-error"><i class="fa fa-warning txt-color-orangeDark"></i> Error requesting <span class="txt-color-red">' + url + '</span>: ' + xhr.status + ' <span style="text-transform: capitalize;">'  + thrownError + '</span></h4>');
		},
		async : true 
	});

}

內容面板上Bootstrap 麪包屑導航

function drawBreadCrumb(opt_breadCrumbs) {
	var a = $("nav li.active > a"),
		b = a.length;

	bread_crumb.empty(), 
	bread_crumb.append($("<li>Home</li>")), a.each(function() {
		bread_crumb.append($("<li></li>").html($.trim($(this).clone().children(".badge").remove().end().text()))), --b || (document.title = bread_crumb.find("li:last-child").text())
	});
	
	// Push breadcrumb manually -> drawBreadCrumb(["Users", "John Doe"]);
	// Credits: Philip Whitt | [email protected]
	if (opt_breadCrumbs != undefined) {
		$.each(opt_breadCrumbs, function(index, value) {
			bread_crumb.append($("<li></li>").html(value)); 
			document.title = bread_crumb.find("li:last-child").text();
		});
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章