【问题标题】:Replace specific content in line in html with JS用JS替换html中一行中的特定内容
【发布时间】:2021-06-10 07:57:42
【问题描述】:

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

感谢您的帮助

【问题讨论】:

    标签: javascript html svg


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      现代 Web 组件(所有现代浏览器都支持)让您获得更大的灵活性

      并将您的 source 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>

      【讨论】:

        猜你喜欢
        • 2021-07-12
        • 2014-04-24
        • 1970-01-01
        • 1970-01-01
        • 2013-09-09
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 2021-08-18
        相关资源
        最近更新 更多