簡體   English   中英

用JS替換html中的具體內容

[英]Replace specific content in line in html with JS

我有一個 html 文件和 JS 文件

所以我在我的 html 文件中有一個 svg 的語法:

<body>
    <svg width="500" height="100">
        <circle id="circle1" cx="20" cy="20" r="10"
        style="stroke: none; fill: #ff0000;"/>  
        <text x="47.872" y="11.064">{home/sensors/temp/kitchen} °C</text>
        <circle id="circle1" cx="20" cy="20" r="10"
        style="stroke: none; fill: #ff0000;"/>
        <title x="47.872" y="11.064" >{home/sensors/temp/bathroom} °C</title>
        <circle id="circle1" cx="20" cy="20" r="10"
        style="stroke: none; fill: #ff0000;"/>
        <text x="47.872" y="11.064">{home/sensors/temp/room} °C</text>
    </svg>
    <script type="text/javascript" src="../scripts/link.js"></script>
</body>
</html>

目前,我的 link.js 中只有這個:

let listTickets = new Map([
                          ['0', '{home/sensors/temp/kitchen}'],
                          ['1', '{home/sensors/temp/bathroom}'],
                          ['2',  '{home/sensors/temp/room}']
]);

let listNumber = new Map([
                          ['0', '24'],
                          ['1', '22'],
                          ['2', '25']
]);

// var topicMatch = line.match(/\{[\w\/]+\}/g); // think need to use regex

所以我想要在我的 js 文件中,當我們在 html 文件中有一個語法時,例如:

"{ + content + }

需要用他的值替換(在我的導航器中而不是在文件中)相同的語法,例如,我們正在讀取 html 文件:

detect first content : {home/sensors/temp/kitchen} => need to change by '24'
detect second content : {home/sensors/temp/bathroom} => need to change by '22'
detect first content : {home/sensors/temp/kitchen} => need to change by '25'

謝謝你的幫助

你可以使用這個 JS 代碼:

var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
  for (let [key, value] of listTickets) {
    if (all[i].innerHTML.includes(value)) {
      all[i].innerHTML=all[i].innerHTML.replaceAll(value, listNumber.get(key));
    }
  }
}

它在您的 html 中的listTickets map 中找到給定字符串的任何匹配項,並使用listNumber map 的值更改它們作為字符串的鍵。

使用現代 Web 組件(在所有現代瀏覽器中支持),您可以獲得更大的靈活性

並將您的SVG 處理為模板文字字符串以替換值(或執行諸如: color之類的功能)

 <temperature-dashboard cold="blue" warm="red"> <template inside template so SVG is not displayed on load> <svg id="temperature" width="100" height="120"> <style> #temperature { background:pink} #temperature circle { stroke:none; r:${size}} </style> <circle cx="20" cy="20" ${color(kitchen)} ></circle> <text x="40" y="25">${kitchen} °C</text> <circle cx="20" cy="60" ${color(bathroom)} ></circle> <text x="40" y="65">${bathroom} °C</text> <circle cx="20" cy="100" ${color(room)} ></circle> <text x="40" y="105">${room} °C</text> </svg> </template> </temperature-dashboard> <script> customElements.define("temperature-dashboard", class extends HTMLElement { connectedCallback() { setTimeout(() => { // wait till innerHTML is fully parsed this.svgsource = this.querySelector("template").innerHTML; let data = { bathroom: 23, kitchen: 24, room: 19 }; this.setdata( data ); }) } setdata( dataIn ){ let fulldata = { size: 15, color: (degrees) => { let coldColor = this.getAttribute("cold"); let warmColor = this.getAttribute("warm"); return `fill="${degrees < 20? coldColor: warmColor }"` }, ...dataIn } const parseTemplateLiteral = (str, data = {}) => { let params = Object.keys(data).join(","); return new Function("p", // Function savely parsing Template Literal "return((" + params + ")=>`" + str + "`)(...Object.values(p))")(data); } this.innerHTML = parseTemplateLiteral(this.svgsource, fulldata); } }); </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM