prettyPrint() only has an effect once. (google-prettify)

≯℡__Kan透↙ 提交于 2019-12-09 23:34:00

问题


I have this JavaScript (with jQuery):

var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
    $('#title-filename').text(filename);
    $('.prettyprint').text(file_contents[key]);
    $('#viewFileModal').modal('show');
}
$(document).ready(function() {
    $(document).on('shown', '#viewFileModal', function(event) {
            prettyPrint();
    });
});

// Variables have been set in code not shown, irrelevant to problem.
// prettyPrint() is called everytime the #viewFileModal is shown,
// but its effect is only felt once.

So prettyPrint() is invoked every time the viewFileModal modal box (courtesy of Bootstrap) is shown, it's just that it only seems to have an effect once per page load.

I have tried commenting out prettyPrint() and entering at the JS console after making the modal box appear. It indeed only has an effect the first time the box is shown (per page load).

Any ideas? I have been stuck on this a while. I also tried putting the call to prettyPrint() in the viewFile function; but the effect is the same.

Thanks a lot.

Sam.


回答1:


Calling "prettyPrint()" adds a class to your PRE tags named "prettyPrinted" after it has been prettified. The line below will remove all instances of the "prettyPrinted" class on your page so that the prettyPrint() function can re-prettify you're PRE tags. This can be done without dynamically adding PRE tags to DIVs.

$('.prettyprinted').removeClass('prettyprinted');



回答2:


Thanks to Matei. Solution was to change to be like this. That is, add whole pre dynamically rather than just text.

var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
    $('#title-filename').text(filename);
    $('#fileblock').html('<pre class="prettyprint">' + file_contents[key] + '</pre>'); // fileblock is a div.
    $('#viewFileModal').modal('show');
}
$(document).ready(function() {
    $(document).on('shown', '#viewFileModal', function(event) {
        prettyPrint();
    });
});

:)




回答3:


Joseph Poff answer is correct but you have to be careful. prettPrint() wraps everything in scan tags. If you remove the prettyprinted class, you aren't removing the scan tags. Unless you are clearing the contents of your pre (or stripping out all the scan tags), every time you recall prettyPrint() you will be adding scan tags, which will wrap your old scan tags. It can get out of control really quickly.



来源:https://stackoverflow.com/questions/16014494/prettyprint-only-has-an-effect-once-google-prettify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!