如何在 JS 中嵌入 HTML 代码

利用注释
var html = function(){
/*
/}除了低版本的firefox,其他浏览器都可以直接通过html变量拿到函数的字面量
之后用正则匹配出注释内容即可。你可以把这块封装为一个函数,类似这样function template (tmpl) {
var regEx = new RegExp("/\
([\S\s])\/", “mg”);
tmpl = tmpl + “”;
var matches = tmpl.match(regEx) || [];
var result = [];
for (var i = 0; i < matches.length; i++) {
result.push(matches[i].replace(regEx, “$1”));
}
return result.join("");
};然后var html = template(function(){
/*

*/
})
注:在某些低版本firefox下获取函数字面量时会过滤注释。如果你的代码需要被一些工具编译,同样有可能被过滤注释。

|
|
|
|
|
|
|
|

--------------------------------------------
-------------------------专题-------------------

猜你喜欢

转载自blog.csdn.net/aliyunshuju/article/details/88288668