我正在使用 Mustache js 和 Accordion 插件。我的想法是使用外部模板文件和外部 json 文件,并将模板文件拉入 Accordion 小部件(使用插件)。一切正常,除了我的 Accordion 不工作。仅当使用警报检查代码时它才有效。 Html 是基本的 Jquery 库调用和保存内容的 div。非常感谢任何帮助。
$(document).ready(function () {
$('head').append("<script id='templateHolder' type='text/template'></script");
$('#templateHolder').load('templates/template.html', function () {
var scripts = ['js/liteaccordion.jquery.js', 'js/mustache.js']; //add as many script as required here
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
$.getJSON('json/data.json', function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
});
//alert('done');
//not working without alert?
$('.jsoncontent').liteAccordion();
});
}
});
});
最佳答案
问题是函数 $.getJSON
是异步执行的,因此指令 $('.jsoncontent').liteAccordion();
在此指令之前执行: $('.jsoncontent').html(info);
当您发出 alert
时,它可能会起作用,因为您正在停止执行,在这种情况下指令 $('.jsoncontent').html(info);
在 $('.jsoncontent').liteAccordion();
执行之前有时间完成。
一种可能的解决方案,也许不是最好的解决方案,但最困难的解决方案可能是使 $.getJSON 的执行同步运行,以替换此代码块:
$.getJSON('json/data.json', function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
});
为此:
$.ajax({
url: 'json/data.json',
dataType: 'json',
success: function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
},
data: {},
async: false
});
编辑
我刚刚注意到您的代码还有另一个重要问题,显然在执行“for”时,您首先加载 Jquery 库,然后加载 Mustache 库。但是您在加载 JQuery 库之后和加载“Mustache”库之前尝试使用函数“Mustache”...这是一个问题。
试试这个:
$(document).ready(function () {
$('head').append("<script id='templateHolder' type='text/template'></script");
$('#templateHolder').load('templates/template.html', function () {
var scripts = ['js/liteaccordion.jquery.js', 'js/mustache.js']; //add as many script as required here
var scriptsLoaded =0;
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
scriptsLoaded++;
if(scriptsLoaded==scripts.length){
$.getJSON('json/data.json', function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
$('.jsoncontent').liteAccordion();
});
}
});
}
});
});
关于jquery - Mustache 和 Jquery 插件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14124012/