我有一段代码将AJAX获取的数据添加到手风琴容器中,现在看起来像这样:
if (document.getElementById('accordion_' + id) == null) {
$("#collapse_group_container").html(
"<div class='panel-group active_subcategory_accordion' id='accordion_" + id + "' data-category-id='" + id + "' data-category-name='" + name + "'>" +
"<div class='panel panel-primary'><div class='panel-heading'>" +
"<h4 class='panel-title'>" +
"<a data-toggle='collapse' data-parent='#accordion' href='#collapse_" + id + "'>" + name + "</a>" +
"<a class='pull-right' style='display:block' onclick='deleteCollapseGroup(" + id + ")'>" +
"X" +
"</a></h4></div><div id='collapse_" + id + "' class='panel-collapse collapse in'>" +
"<div class='panel-body'>" +
"<div class='sk-circle'>" +
"<div class='sk-circle1 sk-child'></div>" +
"<div class='sk-circle2 sk-child'></div>" +
"<div class='sk-circle3 sk-child'></div>" +
"<div class='sk-circle4 sk-child'></div>" +
"<div class='sk-circle5 sk-child'></div>" +
"<div class='sk-circle6 sk-child'></div>" +
"<div class='sk-circle7 sk-child'></div>" +
"<div class='sk-circle8 sk-child'></div>" +
"<div class='sk-circle9 sk-child'></div>" +
"<div class='sk-circle10 sk-child'></div>" +
"<div class='sk-circle11 sk-child'></div>" +
"<div class='sk-circle12 sk-child'></div>" +
"</div>" +
"</div></div></div></div>"
);
}
尽管我认为这可能会让人感到复杂,但我面临的更大问题是我实际上需要在其他地方重复完整的代码。我想知道是否有可能做出这样的事情:
if (document.getElementById('accordion_' + id) == null) {
$("#collapse_group_container").html(
@include('partials/accordion', ['id' => id, 'name' => name])
);
}
或类似,以利用代码重用。我想要包含一个标准html格式的文件,没有引号和插件。
答案 0 :(得分:1)
您可以将javascript函数创建为模板:
var accordionTemplate = function(id, name) {
// your code, returns html string
};
if (document.getElementById('accordion_' + id) == null) {
$("#collapse_group_container").html(
accordionTemplate(id, name)
);
}