JS / Jquery替换内部文本而不破坏事件

时间:2019-01-24 01:33:32

标签: javascript jquery html

这是html:

<div id="div001">
  This is ${Row.1}.
  <p>${Row.2} explain something else.</p>
  <p>${Row.3} welcome you. <span>${Hello.World}, this is a new world.</span></p>
</div>

我要做的是将${Row.1}替换为文本Row 1,而不替换整个div001 DIV。因为这会破坏<p><span>上的事件。

我目前能够遍历所有元素并找到子节点(那里没有html标记),在这种情况下,是第一个<p><span>,并用JQUERY { {1}}。

但是我仍然找不到替换$ {Row.1}和$ {Row.3}的方法。

请告诉我,谢谢。

2 个答案:

答案 0 :(得分:1)

您可以创建一个遍历所有子节点的递归函数,如果它们是文本节点,则替换其文本-如果它们是元素节点,则在其上递归调用该函数:

function replaceTextNodes(elm) {
  elm.childNodes.forEach((node) => {
    if (node.nodeType === 3) {
      // Text node:
      node.textContent = node.textContent.replace(/\${([^}]+)}/g, '$1');
    } else if (node.nodeType === 1) {
      // Element node, recurse:
      replaceTextNodes(node);
    }
  });
}
replaceTextNodes(document.querySelector('#div001'));
<div id="div001">
  This is ${Row.1}.
  <p>${Row.2} explain something else.</p>
  <p>${Row.3} welcome you. <span>${Hello.World}, this is a new world.</span></p>
</div>

答案 1 :(得分:0)

我想到的最简单的方法是将其包装在<span>中。然后,您可以使用$('#div001 > span')定位它:

$('#div001 > span').text('Replaced');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="div001">
  <span>This is ${Row.1}.</span>
  <p>${Row.2} explain something else.</p>
  <p>${Row.3} welcome you. <span>${Hello.World}, this is a new world.</span></p>
</div>

如果您明确要替换${Row.x}组件,则可以将这些部分包装在带有相关ID /类的<span>标记中,并使用它们来定位它们:

$('#one, #three').text('Replaced');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="div001">
  This is <span id="one">${Row.1}</span>.
  <p><span id="two">${Row.2}</span> explain something else.</p>
  <p><span id="three">${Row.3}</span> welcome you. <span>${Hello.World}, this is a new world.</span></p>
</div>


如果您无法更改HTML,那么最好的选择就是使用正则表达式。

以下正则表达式将替换格式为${...}的任何内容:

var element = document.getElementById('div001');
var result = element.innerHTML.replace(/\${\S+}/gm, "REPLACED");
element.innerHTML = result;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="div001">
  This is ${Row.1}.
  <p>${Row.2} explain something else.</p>
  <p>${Row.3} welcome you. <span>${Hello.World}, this is a new world.</span></p>
</div>