用JS替换不同行中的内容

  • 本文关键字:JS 替换 javascript html
  • 更新时间 :
  • 英文 :


我有一个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>

需要用他的值替换相同的语法,例如:

detect 1 : {home/sensors/temp/kitchen} => change by '35'
detect 2 : {home/sensors/temp/bathroom} =>  change by '30'
detect 3 : {home/sensors/temp/kitchen} =>  change by '21'

我在做什么:

let listNumber = new Map([
['{garage/temp}', '35'],
['{home/sensors/temp/kitchen}', '30'],
['{home/sensors/temp/bathroom}', '21'],
]);
var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
for (let [key, value] of listNumber) {
if (all[i].innerHTML.includes(key)) {
all[i].innerHTML=all[i].innerHTML.replaceAll(key, listNumber.get(value));
}
}
}

我没有定义,不明白为什么我有这个

感谢您的帮助

我不确定svg的准确性,但我首先建议不要迭代所有元素,而只迭代svg中的文本元素(querySelectorAll(。

const replacers = [
["{home/sensors/temp/kitchen}", "35"],
["{home/sensors/temp/bathroom}", "30"],
["{home/sensors/temp/room}", "21"],
]
Array.from(document.querySelectorAll("svg > text")).forEach((element) => {
replacers.forEach((replacer) => {
element.textContent = element.textContent.replace(replacer[0], replacer[1]);
})
});
<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>

最新更新