问题描述
https://github.com/S1BIOSE/E-business-Card
我将这些文件放在一个免费的主机上,它使用 HTML、JS 和 CSS。它不支持 PHP。
我想创建令牌来替换 JS、HTML、JSON、XML 和 TXT 文件中的信息。例如:
- 带有公司名称的令牌。
- 带有网站网址的令牌。
- 带有公司描述的令牌。
解决方法
如果没有某种服务器端编程,您就无法动态更改文件。
在前端,您可以在 URL 中包含令牌或通过 AJAX 加载。
以下是在 URL 中使用查询字符串的示例:
function LoadAndApplyTokens() {
const urlParams = new URLSearchParams(window.location.search);
document.querySelectorAll('*').forEach(tag => {
for (let i = 0; i < tag.childNodes.length; i++) {
const child = tag.childNodes[i];
if (child.nodeName.toLowerCase() != '#text') {
continue;
}
let val = child.nodeValue;
let change = false;
let variables = val.match(/::[^:]+::/img);
if (variables == null)
continue;
variables.forEach(variable => {
if (urlParams.has(variable.substr(2,variable.length - 4))) {
const variableValue = urlParams.get(variable.substr(2,variable.length - 4));
while (val.indexOf(variable) >= 0) {
val = val.replace(variable,variableValue);
}
change = true;
}
});
if (change) {
child.nodeValue = val;
console.log(child.parentNode,val);
}
}
});
}
window.addEventListener("load",LoadAndApplyTokens);
<div>
<h1>My name is <b>::name::</b></h1>
<p><b>Description of ::name::</b><br/>::name:: is a company</p>
</div>
<form method="get">
<label>Name: <input name="name" /></label>
<button type="submit">Change</button>
</form>