首页 > 解决方案 > 更改文本

在不影响其余部分的情况下

问题描述

我是 Javascript 新手。我正在尝试使用 Tampermonkey 为 Chrome 编写用户脚本。我设法创建了一些代码来将 a 中的某些单词更改<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命令应该只更改您想要的文本并保持其余部分不变?

标签: javascripttampermonkey

解决方案


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

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

// https://stackoverflow.com/questions/2579666/

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>


推荐阅读