【发布时间】:2016-11-29 09:09:29
【问题描述】:
我有一个相当简单的函数,它会在每次按键时触发。它的作用是在特定条件下(句子很长)标记来自 TinyMCE 的输入文本,然后在 TinyMCE 编辑器中显示突出显示的文本。
乍一看,这就像一个魅力。但是随着文本的增长,数组的执行时间越来越长。
是否有一种绝妙的方法来检测输入光标在文本中的位置,然后只分析周围的单词(例如可能是当前句子)并重用文本的其余部分?
代码是这样的。
HTML
<div id="myTextArea" contenteditable="true">
Just put lorem ipsum here.
</div>
JavaScript (jQuery)
tinymce.init({
selector: '#myTextArea',
height: 300,
setup: function(ed) {
ed.on('change', myCustomInitInstance);
ed.on('keyup', myCustomInitInstance);
ed.on('paste', myCustomInitInstance);
ed.on('cut', myCustomInitInstance);
},
init_instance_callback: "myCustomInitInstance",
});
function myCustomInitInstance(inst) {
var rawText = tinyMCE.get('myTextArea').getContent({
format: 'text'
});
var sentenceArray = rawText.split(".");
var matchWarning = [];
var longSentence = 16;
var words;
var wordCounter;
var output;
for (var i in sentenceArray) {
words = sentenceArray[i].split(" ");
wordCounter = words.length;
if (wordCounter > longSentence) {
matchWarning.push(sentenceArray[i]);
}
}
var editor = tinyMCE.activeEditor;
// Store the selection
var bookmark = editor.selection.getBookmark();
// Remove previous marks and add new ones
$(editor.getBody()).unmark().mark(matchWarning, {
acrossElements: true,
"separateWordSearch": false,
});
// Restore the selection
editor.selection.moveToBookmark(bookmark);
}
欢迎任何关于如何提高速度的建议:)
【问题讨论】:
标签: javascript jquery tinymce