慕森王
下面的功能对我来说很完美:// Note this *is* JQuery, see below for JS solution insteadfunction replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); $(selector).each(function () { var $this = $(this); if (!$this.children().length) $this.text($this.text().replace(matcher, newText)); });}这是一个用法示例:function replaceAllText() { replaceText('*', 'hello', 'hi', 'g');}$(document).ready(replaceAllText);$('html').ajaxStop(replaceAllText);您也可以像这样直接进行替换:document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');但是要小心,因为它也可能会影响标签,css和脚本。编辑: 至于纯JavaScript解决方案,请改用此方法:function replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); var elems = document.querySelectorAll(selector), i; for (i = 0; i < elems.length; i++) if (!elems[i].childNodes.length) elems[i].innerHTML = elems[i].innerHTML.replace(matcher, newText);}