Use Syntax Highlighter on AJAX loaded content

2019-02-04 09:11发布

问题:

How can I use Alex Gorbatchev`s Syntax Highlighter on content loaded after 'window' emits 'load' event? I am trying this way:

    $.ajax({
        url:    file,
        success: function(data) {
            $('.fileName').text(file);
            $('#fileSource > pre').text(data);
            SyntaxHighlighter.all();
        }
    });

... but it is not working. I need to mention that the ajax call can occure at any time after the page loads.

Regards

回答1:

-SyntaxHighlighter.all() binds window load. So if you want to highlight element when the page loads, then use this method.

-SyntaxHighlighter.highlight() highlights elements whenever you will call this method. So it's better you use this.

-SyntaxHighlighter.highlight() takes two parameter, both are optional.

1. Parameter globalParams:

@param {Object} globalParams, Optional parameters which override element's parameters. Only used if element is specified.

2. Parameter element:

@param {Object} element, Optional element to highlight. If none is provided, all elements in the current document are highlighted.

-For more info about this, go to syntaxhighlighter_3.0.83/src/shCore.js



回答2:

I`ve found the answer to my question in one of his examples:

    $.ajax({
        url:    file,
        success: function(code) {
            $('.fileName').text(file);
            var brush = new SyntaxHighlighter.brushes.JScript(),
                html;
            brush.init({ toolbar: false });
            html = brush.getHtml(code);
            document.getElementById('source').innerHTML = html; 
        }
    });


回答3:

just add this section

$(document).ready(function () {
        $('.code').each(function () {
            SyntaxHighlighter.all();
        });
    });