HTML不同页面中重用代码

需求

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

通过 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>

转载于:https://blog.51cto.com/steed/2072722

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值