你可以把你的代码在不同的.html
文件,并http://api.jquery.com/load/
$('#targetid').load('somewhere/a.html'); // loads the .html in the #targetid
main.html中加载它
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
在我看来,如果你想包括HTML和你正在使用PHP,只是使用'include'命令。它将包含HTML。如果它是静态HTML,则不会进行分析。如果它是PHP,它将被解析为PHP。与调用函数相比,它的开销要少很多。 – kainaw
为什么不把它设置在头部作为变量(javascipt) – Derek
看看使用“视图助手”,“部分”等框架。模板引擎也有一些想法。本质上,它的所有“包含”都在下面。如果它没有损坏,请不要修复它。 – ficuscr