本文介绍了JQuery替换特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试图在页面加载时替换内容托管网站上出现转义注册(®)符号的所有实例。基本上,我的问题是这段代码无效: function replaceText(){ $(* ).each(function(){ if($(this).children()。length == 0){ $(this).html($(this).html()。replace ('& reg;','< sup> reg;< / sup>')); } }); } 但是这样做: 函数replaceText(){ $(*)。each(function(){ if($(this).children()。length == 0){ $(this).html($(this).html()。replace('test','⊃& reg;< / sup>')); } }); 解决方案 / p> $(document.body).html($(document.body).html()。replace(/& reg; | / g,⊃& reg;< / sup>)); 这也替换了原始代码中没有的给定对象中的多个符号。 仅供参考,您不必单独查看每个元素。只要您认为这种模式不会合法地出现在HTML属性中,并且只要您在附加任何事件处理程序之前执行此操作,就可以查看正文的HTML并将其全部替换。 如果你想单独遍历每一个元素,你可以使用这个替换逻辑和你的原始代码,如下所示: $($ {code> $(*)。 (this).html($(this).html()。replace(/& reg; |®/ g,'⊃& reg;< / sup>')); } }); 这是一个小提琴: http://jsfiddle.net/jfriend00/DqdwX/ I'm trying to replace all instances where an escaped register (®) symbol appears on a content managed website on page load. Basically, my problem is that this code does not work:function replaceText() { $("*").each(function() { if($(this).children().length==0) { $(this).html($(this).html().replace('®', '<sup>®</sup>')); } });}but this does:function replaceText() { $("*").each(function() { if($(this).children().length==0) { $(this).html($(this).html().replace('test', '<sup>®</sup>')); } });} 解决方案 This seems to work:$(document.body).html($(document.body).html().replace(/®|®/g, "<sup>®</sup>"));This also replaces more than one symbol in a given object which your original code did not.FYI, you don't have to look in every element individually. You could just look in the HTML of the body and replace all there as long as you don't think this pattern would legitimately occur in an HTML attribute and as long as you are doing this before attaching any event handlers.If you want to traverse each element individually, you can use this replace logic with your original code like this:$("*").each(function() { if($(this).children().length==0) { $(this).html($(this).html().replace(/®|®/g, '<sup>®</sup>')); }});Here's a fiddle: http://jsfiddle.net/jfriend00/DqdwX/ 这篇关于JQuery替换特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-30 23:07