使用Javascript进行简单的基于标记的高亮显示

使用Javascript进行简单的基于标记的高亮显示,javascript,ajax,Javascript,Ajax,我得到了这个有效的代码: <html> <head> <title>JS highlighting test</title> <script type="text/javascript"> function highlight() { var t = document.getElementById('highlight').innerHTML;

我得到了这个有效的代码:

    <html>

    <head>

    <title>JS highlighting test</title>

    <script type="text/javascript">

    function highlight()
    {
            var t = document.getElementById('highlight').innerHTML;

            t = t.replace(/(if|switch|for|while)\s*(\()/gi, "<b>$1</b>$2");
            document.getElementById('highlight').innerHTML = t;
    }

    </script>

    </head>

    <body onload="javascript:highlight();">

    <pre id="highlight">
    1  if(foo) {
    2          bar();
    3  }
    4
    3  while(--baz) {
    5          oof();
    6  }
    </pre>

    </body>

    </html>

JS突出显示测试
函数高亮显示()
{
var t=document.getElementById('highlight').innerHTML;
t=t.replace(/(如果开关用于while)s*(\()/gi,$1$2”);
document.getElementById('highlight').innerHTML=t;
}
1如果(foo){
2巴();
3  }
4.
3而(--baz){
5 oof();
6  }
我希望它适用于所有
标记,而不仅仅是一个带有特定和
function doSomethingWithAllPres() { 
    var pres = document.getElementsByTagName("pre");
    for (var i = 0; i < pres.length; i++) { 
        // you can check the class name via pres[i].className === "highlight"
        // (and you should use a class instead of an id therefore)
        if (pres[i].className.indexOf("highlight") >= 0) {
            // action goes here
        }
    }
}
唯一的id,因为它现在的工作。最好是有一个特定的标签组合 有一个特定的id。是否可以扩展上面的小JS函数来解决这个问题 方法(使用一些
文档.getElementsByTag(标记).getElementsById(id).innerHTML
或 在一个循环中有一些相似的东西(我不知道到底是什么满足了需要)?我自己尝试过,但没有真正的成功。我只需要尽可能简单的解决方案,没有什么特别的

谢谢你的想法

--

你几乎猜对了;-)


然而,使用一个框架可能有点过头了…

我尝试了以下方法:函数highlight(){var pres=document.getElementsByTagName(“pre”);for(var I=0;Ipres和带有
id
highlight的元素?如果您将实际的突出显示代码重构为一个函数(例如,函数highlightNode(node){…}),您可以为每个pre和突出显示元素调用该函数。请检查以确保突出显示不是一个
pre
,因此您不会在同一个节点上执行两次。同时,我将此方面添加到我的答案中…您应该应用一个类(而不是id)您可以轻松地检查pre是否在循环中包含此类(但是您应该知道,有效的类名也可能类似于
classA hihglight
,因此您可能应该使用比===更复杂的测试)。
$("pre.highlight").each(function(i) {
    // action goes here
});