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

我是Java语言新手。我正在尝试使用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命令应该只更改您想要的文本,其余部分保持不变?

sunonxg 回答:更改<p>中的文本,而不影响<span>中的其余部分

听起来子元素上有事件侦听器,在这种情况下,重新分配父元素的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>

本文链接:https://www.f2er.com/3169663.html

大家都在问