使用jQuery在页面上包装每个*

我需要在的页面上打包每个星号。 我尝试过的一些事情都行不通。 我认为这归结为我需要在页面中搜索特定的角色,而我无法弄清楚如何做到这一点。

为了不替换整个HTML( 非常糟糕的态度 ),我们可以使用元素进行快速操作:

 var specialTags = ["script", "style"].join("|"), re = new RegExp("^(?:" + specialTags + ")$", "i"); for (var els = document.getElementsByTagName("*"), i = els.length; i--;) { var el = els[i]; if (re.test(el.tagName)) continue; for (var j = 0, childs = el.childNodes, lj = childs.length; j < lj; j++) { var child = childs[j]; if (child.nodeType === 3 && child.nodeValue.indexOf("*") > -1) { var segments = child.nodeValue.split("*"); for (var k = 0, lk = segments.length; k < lk; k++) { el.insertBefore(document.createTextNode(segments[k]), child); if (k < lk - 1) { var span = document.createElement("span"); span.className = "red"; span.appendChild(document.createTextNode("*")); el.insertBefore(span, child); } } el.removeChild(child); } } } 

这是纯JavaScript,不需要jQuery,这在这里无法提供帮助。

演示: http //jsfiddle.net/T4ZXA/5/

不使用jQuery所以它可能会更快一些,并且绝对不依赖于libs:

 (function(str,e){ var regex = new RegExp(str, 'gi'); e.innerHTML = e.innerHTML.replace(regex, '*'); })('*',document.body); 

这个怎么样?…

http://jsfiddle.net/n3Sqn/

  $("body:contains(*)").contents().each(function() { if(this.nodeType == 1) { $(this).html($(this).html().replace(/\*/g, "*")) } }); 

这有点脏和有风险(如下所述),但您可以尝试以下方法:

 var allHTML = $("body").html(); allHTML = allHTML.replace(/\*/g, "*"); $("body").html(allHTML); 

http://jsfiddle.net/6rDK4/

注意:正如Dogbert所指出的,这可能会替换HTML标记内的*字符,例如节点属性。

编辑 :请记住,这可能会重新附加您身体中的所有脚本! 尝试用主容器替换body

EDIT2 :VisioN发布了一个更精细但更安全的解决方案。

这将有效,而不是替换它不应该在标签中的*。

http://jsfiddle.net/DR6Ca/2/

 var text = $("body").find(":contains(*)").contents().filter(function() { //Don't include css or script tags, all other text nodes are fine. return this.nodeType == 3 && ($(this).parent().get(0).tagName.toUpperCase() !== "SCRIPT") && ($(this).parent().get(0).tagName.toUpperCase() !== "STYLE"); }).replaceWith(function() { return this.textContent.replace(/\*/g, "*"); 

你可以测试这个jsfiddle中的其他代码,看看他们是否保持“hi”蓝色。 如果它不是蓝色,他们就有一个bug。