我如何存储<在没有被视为HTML的字符串中?

时间:2017-06-21 04:39:32

标签: javascript jquery

所以我一直在研究一个javascript程序,它用颜色代码来模拟浏览器中的IDE。它查看类.code中的任何代码,查找关键字,现在测试它只是将它们染成红色或蓝色,而我只传递一些关键字。一旦它工作,我会添加更多颜色和关键字。

它现在工作正常,明天我会实施一个检查,试图阻止它出现在单词内的关键字(比如“向前”中的“为”),除了一个问题。

在我的测试代码的底部,我在两行上有<>。出于某种原因,我的代码将这些代码转回<和>因为我的浏览器认为它们是HTML格式,所以这些标志随后会影响我的格式。

function paintKeyword() {
    var spanOpenRed = `<span class="key_red">`;
    var spanOpenBlue = `<span class="key_blue">`;
    var spanClose = `</span>`;
    var index = 1;  //index goes through the keywords which begin at position 1 not 0
    var initCodeString = arguments[0];
    var newCodeString = "";
    var start = 0;
    var end = 0;
    for(index = 1; index <= 3; index++) {
        do {
            end = initCodeString.indexOf(arguments[index],start);
            newCodeString += initCodeString.slice(start,end);
            console.log(newCodeString);
            newCodeString += spanOpenRed + arguments[index] + spanClose;
            start = end + arguments[index].length;
        }
        while(end != -1);
        initCodeString = newCodeString;
        newCodeString = "";
        start = 0;
    }
    for(index = 4; index < arguments.length; index++) {
        do {
            end = initCodeString.indexOf(arguments[index],start);
            newCodeString += initCodeString.slice(start,end);
            console.log(newCodeString);
            newCodeString += spanOpenBlue + arguments[index] + spanClose;
            start = end + arguments[index].length;
        }
        while(end != -1);
        initCodeString = newCodeString;
        newCodeString = "";
        start = 0;
    }
    $(".code").html(initCodeString);
}

(function colorCode() {
    var codeText = $(".code").text();
    paintKeyword(codeText, "function","var","return","for","of","in","new");
})();

请注意,为了练习编写IIFE,我使用了IIFE。但很简单,它所做的就是解析.code类中的任何文本,并用<span class="key_{color}>{keyword}</span>替换关键字。这不是一个完成的代码,现在,除了我问的问题,它做了我打算到目前为止做的事情。我不明白的是为什么它将&lt;&gt;转回角括号以及我可以做些什么来防止它这样做。

如果有帮助,那么正在运行的页面上的.code类中的代码与我的jsfidde中的代码相同:https://jsfiddle.net/jkuhl/z46vmrLe/

这是最底部的四行,<p>标签导致问题。在我的网站上,浏览器将它们视为真正的p标签,尽管我使用&lt;符号,这是我的JavaScript这样做,因为它在我编写程序之前没有这样做。

密码笔:https://codepen.io/jkuhl/pen/vZmjVb

0 个答案:

没有答案
相关问题