将实际的HTML元素添加到PRE/CODE内容中
Add actual HTML elements to PRE/CODE contents
我正在尝试创建一种快速/肮脏的方法,使用javascript为html中的pre/code标记添加一些语法高亮显示。
我遇到的问题是,如果我编辑text()或html(),我会得到转义的内容。也就是说,添加的标签呈现为pre/code,或者我得到了一堆eascape字符。
考虑以下html:
<pre>
<code class="target">
public interface __iIFoo { }
public class __tBar : __iIFoo { }
var list = new List__/__iIFoo'__();
</code>
</pre>
此处的目标是将__iIFoo
的出现替换为:
<span class="interface">IFoo</span>
这样它就可以用css突出显示。当然,当它被渲染时,我不想看到实际的SPAN标记。
以下是我尝试过的:
$(function(){
var iPatt = /__i'w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").text(function(){
return $(this).text().replace(match, replace);
});
});
});
这是有效的,但是,我添加的span标签显示在渲染的内容中,例如,它们就像所有其他预代码一样。我不想看到它!
使用.html()
而不是.text()
。当您使用.text()
时,该值是您希望用户看到的文本,因此它将特殊的HTML字符替换为实体,以便它们能够真实显示。
DEMO
.text()
将值视为文本,.html()
将其呈现为html内容
$(".target").html(function () { //replace text with html
return $(this).text().replace(match, replace);
});
尝试将其与html
一起使用:
$(function(){
var iPatt = /__i'w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").html(function(){
return $(this).text().replace(match, replace);
});
});
});
正如我在评论中所说,更改html而不是文本(fiddle)。
顺便说一句,令人担忧的是,每次遇到匹配时都会完全覆盖.target
的内容。您应该利用RegExp捕获组,只执行一次分配。
(function () {
var iPattern = /__i('w+)/g,
iTemplate = "<span class='interface'>$1</span>";
$(".target").each(function () {
this.innerHTML = this.innerHTML.replace(iPattern, iTemplate);
});
})();
相关文章:
- http://oauth.googlecode.com/svn/code/javascript/oauth.js已关闭,
- 如何从键Code;中获取字符串/字符值;
- jQUery Code没有'我不在IE工作
- 将angular javascript文件包装为“;(function(){..[js-code here]…})()&
- 读取角度表达式json数据中的br或pre或html标记
- 更改<pre>在文本区域更新时阻止内容
- Javascript code to struts2
- 在 Ember 1.0.0 pre 中路由时
- Javascript 计时器只调用一次 Code 隐藏方法
- 将 2D 数组从 Code Behind 传递给 JavaScript
- Joomla javascript var with HTML code
- Pre 标记似乎忽略了样式属性(例如 display:none)
- iframe作为pre元素的嵌套元素
- 使用<代码>或者<pre>Jade模板中的标签
- 从Dart Code调用匿名Javascript函数
- 添加<pre>TinyMce 4中的标签按钮
- this.form.elements.code引用了什么
- 通过将按钮id从Code-behind传递给Jquery Function,Set buttons display no
- Execution of code in <script>
- 将实际的HTML元素添加到PRE/CODE内容中