4

我试图弄清楚如何验证编辑器中的内容,例如,确保内容长度至少为 200 个字符。通常,使用常规文本区域,我可以检索值并从那里验证它。据我了解,这并不容易。

4

2 回答 2

2

我写了一个简单的函数,可以让你计算文档中插入了多少个字符。

/**
 * Returns length of the text inserted to the specified document.
 *
 * @param {module:engine/model/document~Document} document
 * @returns {Number}
 */
function countCharacters( document ) {
    const rootElement = document.getRoot();

    return countCharactersInElement( rootElement );

    // Returns length of the text in specified `node`
    //
    // @param {module:engine/model/node~Node} node
    // @returns {Number}
    function countCharactersInElement( node ) {
        let chars = 0;

        for ( const child of node.getChildren() ) {
            if ( child.is( 'text' ) ) {
                chars += child.data.length;
            } else if ( child.is( 'element' ) ) {
                chars += countCharactersInElement( child );
            }
        }

        return chars;
    }
}

你可以在这里查看它是如何工作的——https: //jsfiddle.net/pomek/kb2mv1fr/

于 2018-05-22T11:50:26.227 回答
-1

CKeditor 有自己的内置函数,用于在文本编辑器中检索数据:

textbox_data = CKEDITOR.instances.mytextbox.getData();//mytextbox is id of textarea 

然后你可以只使用字符串对象的长度属性:

alert(str.length);
于 2018-05-21T03:49:42.867 回答