用JS替换html中的特定内容 [英] Replace specific content in line in html with JS

查看:52
本文介绍了用JS替换html中的特定内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 html 文件和一个 JS 文件

I've got a html file and JS file

所以我的 html 文件中有 svg 的语法:

So I've got a syntax of svg in my html file :

<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 中只有这个:

Currently, I've got only this in my 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 文件中有这样的语法时:

So What I want in my js file, it's when we've got a syntax in html file like:

"{ + content + }

需要用他的值替换(在我的导航器中而不是在文件中)相同的语法,例如,我们正在读取 html 文件:

Need to replace (in my navigator and not in file) the same syntax by his value, for example, we are reading the html file :

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 代码:

You can use this JS code:

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 映射中找到给定字符串的任何匹配项,并使用字符串键的 listNumber 映射的值更改它们.

It finds any match of given strings in the listTickets map in your html, and changes them with the value of listNumber map for string's key.

这篇关于用JS替换html中的特定内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆