我正在开发一个简单的文本屏幕/终端模拟器(类似于JQuery终端插件,但没有RPC的东西和窗口功能).屏幕的每一行都是一个表格行(HTML字符串),并且打印命令可以插入带有一些属性(例如前景色和背景色)的文本.每个打印的文本都包含带有样式属性的跨度,例如:
Afunction getAttr(line, position) { var result = {foreground:'', background:''}, ch = '', i, j = -1, tag = false; // Count characters for (i = 0; i < line.length && j < position; i++) { ch = line.charAt(i); if (ch == '<') { tag = true; } if (ch == '>') { tag = false; } else if (!tag) { j++; } } i--; // Find styles while (i > 0 && line.charAt(i) != '<') { if (line.substr(i, 6) == 'color:') { result.foreground = line.substr(i + 6, 7); } if (line.substr(i, 17) == 'background-color:') { result.background = line.substr(i + 17, 7); } i--; } return result; }
是否有一个更简单的解决方案,不计算字符(可能是JQuery或正则表达式)?
这类似于 所选文本的Get父元素, 但我不需要选择,只需要一个字符索引.