将实际的HTML元素添加到PRE/CODE内容中

Add actual HTML elements to PRE/CODE contents

本文关键字:PRE CODE 添加 HTML 元素      更新时间:2023-09-26

我正在尝试创建一种快速/肮脏的方法,使用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);
    });
})();