更改 <p> 中的文本而不影响 <span> 中的其余部分

Change text in a <p> without affecting the rest in <span>

我是Javascript新手。我正在尝试使用 Tampermonkey 为 Chrome 编写用户脚本。我设法创建了一些代码来将 <p> 中的某些单词更改为缩短版本,但不幸的是,这使得文本的其余部分(包括一些其他代码)无法正常工作。

为了达到这个阶段,我试了一整天。但由于我的知识有限,尽管谷歌搜索如何解决这个问题,我仍然坚持如何继续。

function run () {
        var target = document.querySelector('#dipContainer dip-info-top div.new-dip-info div.col-md-4 div:nth-child(2) div:nth-child(1) p')
        if (target) {
            var str = target.innerHTML;
            str = str.replace(" String to find", "Shortened");
            target.innerHTML = str;
        } else {
            setTimeout(run, 500);
        }
    }
//The below detect any time the <p> changes and run the code to shorten the term. It works.
waitForKeyElements (
    "#dipContainer dip-info-top div.new-dip-info div.col-md-4 div:nth-child(2) div:nth-child(1) p",
    run
);
})();

不幸的是,<p> 在我想要缩短的字符串之后还包含一些其他代码,这些代码允许您单击某些代码以获取一些统计数据。

<span class="player-info-stat">
                        <a class="badge ng-binding disabled" ng-class="{'disabled': history.itemModerationCount === 0}" ng-click="history.itemModerationCount > 0 ? openHistoryModal('itemHistory') : null" data-ol-has-click-handler="">0</a>
</span>

如果我 运行 我的代码更改为缩短的文本,您将无法再单击这些来显示统计信息,即使它仍然会检测是否有可用的统计信息。

有谁知道为什么?根据我的搜索,replace 命令应该只更改您想要的文本而其余部分保持不变?

听起来子元素上有事件侦听器,在这种情况下,重新分配父元素的 innerHTML 会破坏侦听器。

而不是替换 innerHTML,而是搜索文本节点,并将其节点值设置为替换的文本:

// 

function nativeTreeWalker(parent) {
  var walker = document.createTreeWalker(
    parent,
    NodeFilter.SHOW_TEXT,
    null,
    false
  );

  var node;
  var textNodes = [];

  while (node = walker.nextNode()) {
    textNodes.push(node);
  }
  return textNodes;
}

document.querySelector('p').addEventListener('click', () => console.log('p clicked'));
const textNodes = nativeTreeWalker(document.querySelector('#div'));
textNodes.forEach((textNode) => {
  textNode.nodeValue = textNode.nodeValue.replace(/text/g, 'replaced');
});
<div id="div">
  text
  <p>clickable</p>
  text
</div>