texts.json
文件:
[{
"PageTextKeyId": 1,
"PageTextKeyName": "page-first-text",
"PageTextValueName": "Lorem ipsum dolor sit amet"
}, {
"PageTextKeyId": 2,
"PageTextKeyName": "after-page-first-text",
"PageTextValueName": "Consectetuer adipiscing elit"
}, {
"PageTextKeyId": 3,
"PageTextKeyName": "third-text-on-json",
"PageTextValueName": "Sed diam nonummy nibh"
}, {
"PageTextKeyId": 4,
"PageTextKeyName": "this-is-the-forth",
"PageTextValueName": "Euismod tincidunt ut laoreet"
}, {
"PageTextKeyId": 5,
"PageTextKeyName": "last-text-from-the-file",
"PageTextValueName": "Dolore magna aliquam erat volutpat"
}]
index.html
文件:
<!DOCTYPE html>
<html>
<head>
<title>Text from JSON</title>
<meta charset="UTF-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
</head>
<body>
<div id="container" class="some-class">
<p>[page-first-text] - [page-first-text]</p>
<div id="creatives">
<b>[after-page-first-text]</b>
<div>
<span>
<i>[third-text-on-json]</i>
</span>
</div>
</div>
<div class="holder">
<div id="sfc">
<div id="designer">
<a href="#">[this-is-the-forth]</a>
</div>
<div id="developer">
<div>
<div class="designer-class">
<a href="#">
<span>[last-text-from-the-file]</span>
</a>
</div>
</div>
</div>
</div>
</div>
<script src="script.js" ></script>
</div>
</body>
</html>
这只是一个示例的 html
,它也可以在没有 id
或 class
的 DOM 中有很多的 [text-here]
。
这是 script.js
:
(function() {
var jsonRequest = new XMLHttpRequest();
jsonRequest.open('GET', 'texts.json');
jsonRequest.setRequestHeader("Content-Type", "application/json");
jsonRequest.onload = function() {
var jsonContent = JSON.parse(jsonRequest.responseText);
/* NEED HELP HERE */
}
jsonRequest.send();
})();
我希望能够动态替换网页中以"["和"]"开头结尾的html
字符串,将其中的值替换成json
文件中对应的值(仅在浏览器中查看页面时进行替换),不做永久更改。
浏览器上的示例输出:
...
<body>
<div id="container">
<p>Lorem ipsum dolor sit amet</p>
<div id="creatives">
<b>Consectetuer adipiscing elit</b>
<div>
<span>
<i>Sed diam nonummy nibh</i>
</span>
</div>
</div>
<div id="holder">
<div id="sfc">
<div id="designer">
<a href="#">Euismod tincidunt ut laoreet</a>
</div>
...
我希望可能有一个正则表达式的解决方案,例如:
var everyDom = document.getElementsByTagName('*');
for (var i=0; i<everyDom.length;i++) {
/*
check with regex if dom value starts with "[" and end with "]"
if true replace value with json value from key-name
else go and look for other doms
*/
}