如果在 div 中找到,则替换某些文本(仅适用于最后一行)

replace certain text if found in div (only working last line)

 let maskElm = '#div-popUp';
 setTimeout(function() {
    $(maskElm).each(function() {
        let text = $(this).html();
        console.log(text);
        
        $(this).html(text.replace('asID', 'DE ID (FFF)'));
        $(this).html(text.replace('LG NAME', 'The Long Name'));
        $(this).html(text.replace('TYPE', 'S12 Type'));
        $(this).html(text.replace('TOWER424', 'Tower')); <-- only line that works as expected, rest ignored, why?
    });
}, 50);

运行 以上,仅更新最后一个文本(按预期工作)。在我的 maskElm 弹出窗口 div 中,上述所有字段都存在,甚至在我的 console.log(text); 中显示了输出 - 但前 3 个文本替换被忽略了。我在这里缺少什么? 注意:我需要用 .html 逐行完成,因为我不想松散格式..

我真的需要对每个文本值另外添加 if 检查吗?我已经有大约 20 个其他字段需要添加。最佳路线?

你应该在.replace后保存变量

let text = $(this).html();
text = text.replace('asID', 'DE ID (FFF)');
text = text.replace('LG NAME', 'The Long Name');
text = text.replace('TYPE', 'S12 Type');
text = text.replace('TOWER424', 'Tower');

然后写入元素:

$(this).html(text);

您可以使用一组旧值和新值来简化操作。您可以获得元素的 HTML 内容,遍历值以替换并更新 DOM 一旦所有这些都被替换:

let maskElm = "#div-popUp";
let toReplace = [
  { "asID": "DE ID (FFF)" },
  { "LG NAME": "The Long Name" },
  { "TYPE": "S12 Type" },
  { "TOWER424": "Tower" }
];

$(maskElm).each(function () {
  let updatedHTML = $(this).html();

  toReplace.forEach((item) => {
    const [oldValue, newValue] = Object.entries(item)[0];
    updatedHTML = updatedHTML.replace(oldValue, newValue);
  });

  $(this).html(updatedHTML);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div-popUp">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat aspernatur <b>TYPE</b> eligendi error in consectetur incidunt, <b>asID</b> voluptas autem dolorem deserunt <b>LG NAME</b> praesentium voluptatum eius, rerum magnam laborum id. Porro <b>TOWER424</b> nemo dolore aut.</div>