分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

HTML不同页面中重用代码

发布时间:2023-09-06 01:43责任编辑:蔡小小关键词: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>

HTML不同页面中重用代码

原文地址:http://blog.51cto.com/steed/2072722

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved