我有一个单页动态网页。当用户单击某些按钮时,应用程序的整个布局都会更改。
我目前执行此操作的方法是,清除页面的全部内容,并对需要添加的html每行进行硬编码。
换句话说,我有一个javascript / jquery脚本,可以清除所有内容并手动逐个手动添加每个元素。而不是解析先前存在的文件或更聪明的文件。
我想有一个用html和jinja编写的模板(如果可能),然后加载该信息。也就是说,清除页面的全部内容,然后将其设置为模板。
但是我不确定该怎么做。
例如,这是创建页面的尝试:
function setResume() {
setElementToFile("MainText", "static/resume.txt");
$('head').empty();
$('head').append('<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>');
$('head').append('<link rel="stylesheet" type="text/css" href="static/general.css"/>');
$('head').append('<link rel="stylesheet" type="text/css" href="static/resume.css"/>');
$(".TopHeader").css("margin-left", "10%");
$("article").empty()
var more_info = $('<div class="TopHeader"></div> id="SecondHead"');
more_info.append(
$('<a target="_blank" href="https://github.com/Makogan">\
<img src="static/images/GitHub-Mark.png" width="64px" height="64px" alt="github">\
</a>'));
more_info.append(
$('<a target="_blank" href="https://gitlab.com/Makogan">\
<img src="static/images/gitlab_logo.png" alt="github" width="64px" height="64px">\
</a>'));
more_info.append(
$('<a target="_blank" href="https://www.linkedin.com/in/camilo-talero-3906a9167/">\
<img src="static/images/linkedin_logo.png" alt="github" width="64px" height="64px">\
</a>'));
more_info.append(
$('<a target="_blank" href="https://www.linkedin.com/in/camilo-talero-3906a9167/">\
<img src="static/images/mail.png" alt="github" width="64px" height="64px">\
</a>'));
$(".TopHeader").after(more_info);
clearButtons();
document.getElementById("resume_button").style.backgroundColor =
"rgba(25, 129, 190, 0.7)";
}
function clearButtons()
{
var x = document.getElementsByTagName("button");
var i;
for (i = 0; i < x.length; i++) {
var color = getComputedStyle(document.body).getPropertyValue('--button_background_color');
x[i].style.backgroundColor = color;
}
}
function setElementToFile(elementID, file)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(elementID).innerHTML =
this.responseText;
}
};
xhttp.open("GET", file, true);
xhttp.send();
}
答案 0 :(得分:1)
也许您正在寻找jquery“ .load()”函数 http://api.jquery.com/load/
您可以使用其他html文件,并在单击按钮时动态加载它们:
<button type="button" id="button1" name="button1">Load content 1</button>
<button type="button" id="button2" name="button2">Load content 2</button>
<div id="content_div">
</div>
<script>
$(function() {
$("#button1").click(function () {
$("#content_div").load("content1.html");
})
$("#button2").click(function () {
$("#content_div").load("content2.html");
})
});
</script>
如果访问页面时默认需要“ content_div”包含某些内容,则可以使用:
<script>
$(function() {
$("#content_div").load("content_default.html");
});
</script>
答案 1 :(得分:0)
我建议您看一下JS模板引擎,例如Handlebars或Mustache。
这将使您可以在单独的模板文件中定义页面内容/布局,并在用户交互时调用框架以提取所需的任何模板并进行呈现。
抱歉,如果您需要帮助解决这些库中的任何一个问题,我没有提出具体的建议,我建议您发布一个尖刻的问题。这已经很广泛了。