javascript - 更改文本
在不影响其余部分的情况下
问题描述
我是 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
命令应该只更改您想要的文本并保持其余部分不变?
解决方案
听起来子元素上有事件侦听器,在这种情况下,重新分配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>
推荐阅读
- delphi - Datasnap 会话已过期
- ios - 如何在 ios ionic build 中解决“'FIRInstanceID' 没有可见的@interface 声明选择器'token'”
- html - 我的本地 Html Ref 由于某种原因无法正常工作
- single-sign-on - SSO 在不同浏览器中的工作功能
- python - 使用 ColumTransformer/FeatureUnion 后构建完整数据框(特征值 + 名称)的推荐方法是什么?
- javascript - 带有 Laravel 和 Vue.js v-model 问题的待办事项列表
- apache-kafka - 从 kafka 流中读取 peek 主题
- javascript - 使用 react-bootstrap 或 material-ui 反应复选框状态管理?
- typescript - 如何将元素添加到数组中的json数组?
- java - MyBatis 生成器包括视图