前端页面如何引入公用的页面header和footer

很多时候我们做网站开发的时候会遇到一个比较有趣的问题,那就是我们每个页面使用的footer和header,于是当然我们有办法在每个页面都相同的html标签,显然这样代码的复用程度是很低的,我们需要想到的是能不能仅仅在页面上仅仅引用一个div就可以把整个页面的头都引用过来,当然是可以实现的

那么应该怎样来实现这样的效果,首先我们要引用公共的页面也是模板,我们是不是应该有一个有一个模板:header.templet.html,我们就在模板中写点内容:

<meta charset="utf-8"/>
<div class="inc_header">
<span>当前登录用户</span><span id="inc_loginname"></span>
</div>

我们可以将模板放在项目中一个文件夹里面,在我的项目中我是这样存放的:



上面是我们对文件的存放,在项目中的位置,接下来需要做的事情是在对应的页面对应的js文件中引入header.inc.html文件了

如何引入:

var Include = function(cfg) {
		this.cfg = cfg;

		this._init();
	};

	Include.prototype = {
		constructor : Include,

		_init : function() {
			var c = this.cfg;

			if (c.async !== false)
				c.async = true;

			this.$container = $('#' + c.id);
		},

		fetch : function() {
			var c = this.cfg, self = this;

			return $.ajax({
				url : c.src,
				type : 'GET',
				dataType : 'html',
				async : c.async,
				success : function(html) {
					self.$container.html(html);
					c.onload && c.onload(html);
				}
			});
		}
	};
	// 需要引入的代码片段
	var includes = [ {
		id : 'header',
		src : 'resources/views/common/header.inc.html',
		onload : function() {
			// console.log('...header loaded...');
		}
	}, {
		id : 'footer',
		src : 'footer.inc.html',
		onload : function() {
			// console.log('...footer loaded...');
		}
	} ];

	$.each(includes, function(i, cfg) {
		if ($('#' + cfg.id).length) {
			new Include(cfg).fetch();
		}
	});


猜你喜欢

转载自blog.csdn.net/datouniao1/article/details/79821088
今日推荐