我正在尝试编写一个 Chrome 扩展程序,以用自定义文本替换网页中所有特定出现的文本。
我在 SO 中发现了类似的问题,并尝试了以下解决方案,但它似乎不起作用。
config.text_config = [
{
src: "Lorem ipsum",
target: "live long and prosper"
}
]
config.text_config.forEach(function (obj) {
$('*').each(function () {
var text = $(this).text().replace(obj.src, 'REPLACEMENT_TEXT');
$(this).text(text);
})
});
有人可以帮我一下吗?
最佳答案
您可以执行类似的操作,以确保替换所有节点的文本:
$(function () {
$.fn.getTextNodes = function(contentText) {
return $(this).find(":not(iframe)").addBack().contents().filter(function() {
return this.nodeType == 3 && this.nodeValue.indexOf(contentText) != -1;
});
};
var config = {}
config.text_config = [
{
src: "Lorem ipsum",
target: "live long and prosper"
}
];
config.text_config.forEach(function (obj) {
var re = new RegExp(obj.src, 'g');
$('*').getTextNodes(obj.src).each(function(item, element) {
this.nodeValue = this.nodeValue.replace(re, 'REPLACEMENT_TEXT');
});
});
});
<script src="//code.jquery.com/jquery-1.11.3.js"></script>
<div id="Message area">
<div class="selected-div">
Operation Lorem ipsum Lorem ipsum 1
</div>
<div class="selected-div">
Operation Lorem ipsum Lorem ipsum 2
</div>
<div class="selected-div">
Operation Lorem ipsum Lorem ipsum 3
</div>
<div class="selected-div">
Operation Lorem ipsum Lorem ipsum4
</div>
</div>
关于javascript - 用 jQuery 替换 DOM 中出现的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556960/