javascript 在所有商标和注册商标符号周围添加上标 <sup> 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19364581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding superscript <sup> tags around all trademark and registered trademark symbols
提问by Ty Bailey
I am trying to add <sup></sup>
tags around every ™, ®, © in my page.
我正在尝试<sup></sup>
在我的页面中的每个 ™、®、© 周围添加标签。
I found this question: CSS superscript registration trademarkwhich helped get me started.
我发现了这个问题:帮助我入门的CSS 上标注册商标。
The script works in the sense that the tags are being placed in the proper locations, but it is adding two <sup></sup>
tags around each instead of just one.
该脚本的工作原理是将标签放置在适当的位置,但它<sup></sup>
在每个标签周围添加了两个标签,而不是一个。
Here is my JS adding the tags:
这是我的 JS 添加标签:
jQuery("body").html(
jQuery("body").html().replace(/®/gi, '<sup>®</sup>').replace(/?/gi, '<sup>®</sup>').
replace(/™/gi, '<sup>™</sup>').
replace(/?/gi, '<sup>™</sup>').
replace(/©/gi, '<sup>©</sup>').
replace(/?/gi, '<sup>©</sup>')
);
How can I make sure the tags are only added once per symbol? A conditional of some sort maybe?
如何确保每个符号只添加一次标签?也许是某种条件?
回答by VisioN
Instead of rewriting the entire markup (and removing all bound events), I'd go for something like that:
而不是重写整个标记(并删除所有绑定事件),我会去做这样的事情:
$('body :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace(/[???]/g, '<sup>$&</sup>');
});
回答by Timon de Groot
@VisioN's answer didn't work that well for me, although it was facing the right direction. I tweaked it a little bit:
@VisioN 的回答对我来说效果不佳,尽管它正朝着正确的方向发展。我稍微调整了一下:
var regexp = /[\xAE]/;
$('body :not(script,sup)').contents().filter(function() {
return this.nodeType === 3 && (regexp.test(this.nodeValue));
}).replaceWith(function() {
return this.nodeValue.replace(regexp, '<sup>$&</sup>');
});
This method makes use of the character hex, instead of using the character code. I looked up the hex on character-codes.comand picked the character hex of the ? character. The value is AE
so that's how I got to my solution. Let me know if this one worked for you!
此方法使用字符 hex,而不是使用字符代码。我在character-codes.com上查找了十六进制并选择了 ? 特点。价值就是AE
这样我得到了我的解决方案。让我知道这是否适合您!
回答by David Feldt
This works for me.
这对我有用。
$("p,h1,h2,h3,h4,li,a").each(function(){
$(this).html($(this).html().replace(/®/gi, '<sup>®</sup>').replace(/?/gi, '<sup>® </sup>'));
});
回答by hockey2112
This worked for me on my Drupal 8 website:
这在我的 Drupal 8 网站上对我有用:
(function ($, Drupal) {
var regexp = /[\u2122]/;
$('body :not(script,sup)').contents().filter(function() {
return this.nodeType === 3 && (regexp.test(this.nodeValue));
}).replaceWith(function() {
return this.nodeValue.replace("\u2122", "<sup>™</sup>");
});
})(jQuery, Drupal);