ian*_*her 41 html javascript templates
我正在努力为我的问题找到一个干净的解决方案,并想知道是否有人可以提供一些提示.
我有"templates.html",其中包含一些HTML片段,我想将其加载到JavaScript中并使用.访问模板/片段的好方法是什么,记住templates.html不是加载的DOM文档?
我正在考虑使用document.open
创建DOM来访问,但我认为这在某些浏览器上存在问题.
pet*_*erp 44
使用jQuery和.load()
(http://api.jquery.com/load/
)方法将加载的文档注入DOM.
$(function() {
$('#content').load('/templates.html');
});
Run Code Online (Sandbox Code Playgroud)
kle*_*had 23
你可以将html加载到一个隐藏的div中然后你将有一个DOM访问权限,最简单的方法是将html加载到DIV使用jquery load:http://api.jquery.com/load/
$( "#result" ).load( "ajax/test.html" );
Run Code Online (Sandbox Code Playgroud)
ola*_*nod 17
这有点旧,但是现在"加载HTML模板与JavaScript"应该引用加载HTMLTemplateElement
这里是一种更现代的方法来加载本机模板与javascript也适用于您的用例.
首先使用<template>
已经比将HTML加载到隐藏的DIV中更好,因为模板是不可见的并且不显示内容.您可以从头开始呈现模板,并在需要时使用它们.
<html>
<head>
<template>My template</template>
</head>
<body>
<script>
document.body.append(
document.importNode(
document.querySelector('template').content,
true
)
)
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
或者动态创建它们.
const template = document.createElement('template')
// modify the template's content
template.content.append(document.createElement('div'))
// add it to the document so it is parsed and ready to be used
document.head.append(template)
Run Code Online (Sandbox Code Playgroud)
因为我们希望基于我们从网络获得的某些文本来构建模板的内容,所以我们必须解析它并将其添加到我们的template.content
.
const text = fetchTemplateSomehowAsText('my-template.html')
const parsedDocument = new DOMParser().parseFromString(text, 'text/html')
template.content.append(parsedDocument.querySelector('#my-snippet'))
Run Code Online (Sandbox Code Playgroud)
如果my-template.html
已经包含在<template>
标记中,我们可以避免手动创建模板元素,因为DOMParser已经为我们创建了模板元素.
document.head.append(
new DOMParser().parseFromString(text, 'text/html')
.querySelector('template')
)
)
Run Code Online (Sandbox Code Playgroud)
这是我用来将模板动态加载到文档中的片段,使用我刚才解释的内容.
And*_*tre 10
另一种方法是使用requireJS.
require (['text!template_name'], function(yourTemplate) {
// do stuff in here with yourTemplate dinamically load
}
Run Code Online (Sandbox Code Playgroud)
对于简单的要求,您可以尝试:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
//do something with xhr.responseText
}
};
xhr.open('GET', '/template.html');
xhr.send();
Run Code Online (Sandbox Code Playgroud)