【发布时间】:2013-04-15 11:53:50
【问题描述】:
我有这个 JavaScript(带有 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.
所以每次显示 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