项目中新建一个template文件夹,再新建一个jquery_template_beta.js文件 在js文件中粘贴如下代码
if ( jQuery) {
window. addEventListener ( 'message' , function ( event ) {
var search = event. data. search;
var attrs = '' ;
if ( search) {
var ms = search. match ( / [a-z]+=((?!&).)+ / g ) ;
if ( ms && Array. isArray ( ms) ) {
for ( var i = 0 ; i < ms. length; i++ ) {
var arr = ms[ i] . split ( '=' ) ;
attrs += ' ' + arr[ 0 ] + '="' + arr[ 1 ] + '"' ;
}
if ( attrs) attrs = attrs. trim ( ) ;
}
}
if ( event. data. head) window. document. head. innerHTML += event. data. head;
$ ( 'iframe.base_html_template' ) . replaceWith ( '<script type="text/template"' + attrs + '>' + event. data. body + '<\/script>' ) ;
} ) ;
}
在使用的html页面中想要插入的位置加入一段如下,这样运行的时候就会自动处理替换了,这实现了一个template1.html
页面可被多次复用
< html>
...
< iframe class = " base_html_template" src = " ../template1.html" id = " template1" > </ iframe>
...
</ html>
忘了说,template1.html
页面就是一个模板页,自己写得没什么区别,写出来是如下这样子的,
< html>
< head>
< style>
h3.h {
color : blue;
}
</ style>
</ head>
< body>
< h3 class = " h" > 这是一个模板页</ h3>
</ body>
</ html>
需要注意的地方:
(没用过就不管)使用HBuilderX开发工具上运行内置浏览器是会出现问题的,因为有被系统加入了自动刷新逻辑 每个模板页都是独立的,模板页都有写内部样式,且样式名前面都加一个命名就好(类似命名空间),避免复用的时候样式被混肴,错乱。