您的位置:首页 > Web前端 > HTML

HTML不同页面中重用代码

2018-02-24 19:55 633 查看

需求

几个页面需要的头部和底部的内容往往是一样的,这就希望可以只写一段代码作为模板,然后再几个页面中都加载这这个模板。另外,如果需要修改,也只要修改模板就好,所有页面都同时都是新的样式了。

通过 JavaScript 来实现

能实现上面需求的方法还是不少的,这个比较简单一点,几乎不需要学习的额外知识,只通过2句基本的js语句就能实现。一句写页面html,一句加载js文件执行。暂时先用了这个方法。

第一步:制作html文件

把你的代码正常写成一个html文件,比如:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="background: black;height: 36px;line-height: 36px;color: #9f9f9f;">
<div style="width: 1000px;margin: auto;">
<span>
欢迎光临,请
<a href="login.html" style="text-decoration: none;color: red;">登录 </a>
或者
<a href="regist.html" style="text-decoration: none;color: red;">注册</a>
</span>
<ul style="float: right;list-style-type: none;margin: 0">
<li style="float: left;margin: 0 5px;padding: 0 10px;">
<a href="cart.html" style="text-decoration: none;color: red;">购物车</a>
</li>
<li style="float: left;margin: 0 5px;padding: 0 10px;">我的订单</li>
<li style="float: left;margin: 0 5px;padding: 0 10px;">客户服务</li>
</ul>
</div>
</div>
</body>
</html>

第二步:转成js文件

就是把上面的每一行,都用
document.writeln(" ")
包起来。把你的html的内容都写在括号里。例外注意引号需要用
\"
转义。这个工作写个简单的脚本就能完成、不过也有现成的在线工具:http://tool.chinaz.com/Tools/Html_Js.aspx

最后你的js文件是这样的,这里我只需要body内的部分:

document.writeln("<div style=\'background: black;height: 36px;line-height: 36px;color: #9f9f9f;\'>");
document.writeln("    <div style=\'width: 1000px;margin: auto;\'>");
document.writeln("        <span>");
document.writeln("            欢迎光临,请");
document.writeln("            <a href=\'login.html\' style=\'text-decoration: none;color: red;\'>登录 </a>");
document.writeln("            或者");
document.writeln("            <a href=\'regist.html\' style=\'text-decoration: none;color: red;\'>注册</a>");
document.writeln("        </span>");
document.writeln("        <ul style=\'float: right;list-style-type: none;margin: 0\'>");
document.writeln("            <li style=\'float: left;margin: 0 5px;padding: 0 10px;\'>");
document.writeln("                <a href=\'cart.html\' style=\'text-decoration: none;color: red;\'>购物车</a>");
document.writeln("            </li>");
document.writeln("            <li style=\'float: left;margin: 0 5px;padding: 0 10px;\'>我的订单</li>");
document.writeln("            <li style=\'float: left;margin: 0 5px;padding: 0 10px;\'>客户服务</li>");
document.writeln("        </ul>");
document.writeln("    </div>");
document.writeln("</div>");

第三步:到你的页面文件中加载这个js文件

把这句放在你的body的第一行,这样的的头部内容就有了:

<script src="page/pg-top.js"></script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javas cript