嘿,我有一块 HTML 代码,我将会反复使用它(在用户访问的不同时间段内,而不是一次性使用)。我认为最好的方法是创建一个 HTML div,将其隐藏起来,需要时获取其 innerHTML,并对几个关键词进行 replace() 操作。以下是示例 HTML 代码块...
<div id='sample'>
<h4>%TITLE%</h4>
<p>Text text %KEYWORD% text</p>
<p>%CONTENT%</p>
<img src="images/%ID%/1.jpg" />
</div>
用动态数据替换这些关键字的最佳方式是什么?是否应该使用正则表达式,或者有更好的方法?
template = document.getElementById('sample');
template = template.replace(/%TITLE%/, some_var_with_title);
template = template.replace(/%KEYWORD%/, some_var_with_keyword);
template = template.replace(/%CONTENT%/, some_var_with_content);
template = template.replace(/%ID%/, some_var_with_id);
感觉我选了一种愚蠢的方法来做这件事。 有人有任何建议可以更快、更聪明或更好地完成吗?这段代码会在用户访问期间经常执行,有时甚至每3-4秒钟就会执行一次。
提前致谢。