如何使用语法荧光笔获取行总数

How to get the total number of lines with SyntaxHighlighter

本文关键字:获取 荧光笔 何使用 语法      更新时间:2023-09-26

是否可以使用语法高亮笔(http://alexgorbatchev.com/SyntaxHighlighter/)获得源代码的行数?

我可以使用这里定义的技术:如何获取文本区域中的行数?但也许 SyntaxHighlight 可以更容易地做到这一点。

谢谢。

我不

相信有内置的解决方案,但这里有一个函数可以解决问题。它使用 getElementsByClassName 方法,因此我认为它不适用于 IE8 或更低版本。如果您愿意,可以使用您喜欢的 DOM 查询库。

/**
 * Returns the number of lines in a SyntaxHighlighter code block.
 *
 * @param {Element} node The top-level DOM element containing the code block.
 * @return {Number} The number of code lines, or 0 if not found.
 */
function getLineCount(node) {
    var codeNode;
    var containerNode;
    if (node && typeof node.getElementsByClassName === 'function') {
        codeNode = node.getElementsByClassName('code');
        if (codeNode.length) {              
            containerNode = codeNode[0].getElementsByClassName('container');
            if (containerNode.length) {
                return containerNode[0].children.length;
            }
        }
    }
    return 0;
}

jQuery版本,因为显然这是一回事。

function getLineCount(node) {
    return $(node).find('.code .container').children().length;
}