0

I'm trying something out, just for a bit of fun really, whereby I'm trying to emulate syntax highlighting when code is entered into a textarea on webpage.

I've written a little JS script, but It's throwing errors. "cannot set property 'color' of undefined."

To do this I have created a small array of a few example 'buzzwords' to search the entered code for. Then I have split the code string into an array and looped for matches between the two. I'm not that familiar with the split method or indeed the search method. How can I get any matches that are found to change colour on the screen in real time?

function init() {

window.setInterval(function() {
    var code = document.getElementById("texty").value;
    var buzzword = ["function","()","{","}","[","]",".getElementById",".getElementsByClassName",".style","$"];
    for(i=0; i < buzzword.length; i++) 
    {
        var testers = code.split(" ");
        for(i =0; i < testers.length; i++) 
        {
            if(buzzword[i] == testers[i]) 
            {
                code.search(testers[i]);
                code.match(testers[i]).style.color = 'blue';
            }
        }
    }
}, 10000);

}

function init() is executed onFocus of the textarea.

Any help would be appreciated, thanks!

4

2 回答 2

0

我决定再试一次。正确地安静,我之前的答案被击落了。这是一些代码。我无法对其进行 jsfiddle 操作,但我已经对其进行了测试,并且效果很好:

一些CSS:

<style> .blue { color: blue; } </style>

一些用于测试的 HTML:

<div id="div"></div>
<textarea id="area" onfocus="init()">
  function writeTo() {
    var id = document.getElementById('id');
    var class = document.getElementsByClass('class');
    id.style.color = 'blue';
    var $id = $('#id');
    var array = [];
    var obj = {};
  }
</textarea>

一些Javascript。这使用正则表达式而不是数组。它对流行语进行查找/替换,用class="blue". 然后将文本转储到 awaiting div

function init() {
  var area = document.getElementById('area');
  var div = document.getElementById('div');
  var buzzword = /function|.getElementById|.getElementsByClassName|.style|\{|\}|\(|\)|\$|\[|\]/g;
  var text = area.value;
  var replacedText = text.replace(buzzword, function (selection) {
    return '<span class="blue">' + selection + '</span>';
  });
  div.innerHTML = replacedText;
}

如果您希望它实时更新(或每次用户键入内容时),您应该将keyup事件绑定到 textarea 以init每次运行。这里还有更多内容。

您应该摆脱您的onfocus事件并添加它:

if (window.addEventListener) {
  document.getElementById('area').addEventListener('keyup', init, false);
} else {
  document.getElementById('area').attachEvent('keyup', init);
}

这将确保当您输入 . 时textarea,语法着色应该可以在div. 确保对 Javascript 的调用位于 HTML 页面的底部,而不是位于标题中,否则它将无法识别该元素。

于 2013-09-07T12:49:37.833 回答
0

我会做这样的事情:

var buzzwords = ['\\(\\)', 'function'];
previewDiv.innerHTML = textarea.value.replace(new RegExp(
    '(' + buzzwords.join('|') + ')', 'g'
), '<span style="color:blue">$1</span>');

不要忘记使用两个反斜杠转义特殊字符 : .(){}[]$

于 2013-09-07T14:49:38.020 回答