【问题标题】:prettyPrint() only has an effect once. (google-prettify)prettyPrint() 只产生一次效果。 (谷歌美化)
【发布时间】:2013-04-15 11:53:50
【问题描述】:

我有这个 JavaScript(带有 jQ​​uery):

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.

所以每次显示 viewFileModal 模态框(由 Bootstrap 提供)时都会调用 prettyPrint(),只是它似乎在每次页面加载时只产生一次效果。

我尝试注释掉prettyPrint(),并在出现模态框后在JS控制台输入。它确实只在第一次显示该框时(每页加载)才有效果。

有什么想法吗?我一直坚持这一点。我还尝试在 viewFile 函数中调用prettyPrint();但效果是一样的。

非常感谢。

山姆。

【问题讨论】:

  • 每次页面加载只显示一次是什么意思?每次打开模态窗口时都不会调用 prettyPrint?您是否尝试使用show 事件,而不是shown
  • 我的意思是,只有刷新页面并单击按钮以再次显示模式时,它才会再次起作用。我将shown 更改为show,它的工作原理相同。prettyPrint() 肯定被称为它只是 no 对语法突出显示第二次或更多次的影响。
  • 在调用prettyPrint()之前添加这行代码,看看有没有变化:$('pre code').not('.prettyprint').addClass('prettyprint');
  • 你确定你在#viewFileModal里面有<pre><code>吗?您正在使用 .text() 函数,据我所知,它不会解析 html 代码。所以您可以尝试使用 .html() 而不是 .text()
  • 我设法修复了它。谢谢你的帮助,你让我明白了我应该改变什么。解决方案是动态添加<pre class="prettyprint"> 块,而不是尝试在仅更改文本的现有块上调用prettyPrint()。我将在下面发布解决方案。

标签: javascript jquery modal-dialog prettify


【解决方案1】:

在美化之后调用“prettyPrint()”会在你的 PRE 标签中添加一个名为“prettyPrinted”的类。下面的行将删除页面上“prettyPrinted”类的所有实例,以便 prettyPrint() 函数可以重新美化您的 PRE 标签。这可以在动态添加 PRE 标记到 DIV 的情况下完成。

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

【讨论】:

    【解决方案2】:

    感谢马太。解决办法是改成这样。 也就是说,动态添加整个 pre 而不仅仅是文本。

    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 的答案是正确的,但您必须小心。 prettPrint() 将所有内容包装在扫描标签中。如果你删除了 prettyprinted 类,你并没有删除扫描标签。除非您正在清除 pre 的内容(或剥离所有扫描标签),否则每次调用 prettyPrint() 时,您都会添加扫描标签,这将包装您的旧扫描标签。它很快就会失控。

      【讨论】:

      • 感谢您的建议。
      猜你喜欢
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多