我正在努力尋找乾淨的解決方案來解決我的問題,並想知道是否有人可以提供一些提示。使用JavaScript加載HTML模板
我有「templates.html」,其中包含我想加載到JavaScript並使用的HTML片段的集合。記住templates.html不是加載的DOM文檔,訪問模板/代碼片段的好方法是什麼?
我在想使用document.open
來創建一個DOM來訪問,但我認爲這在某些瀏覽器上有問題。
我正在努力尋找乾淨的解決方案來解決我的問題,並想知道是否有人可以提供一些提示。使用JavaScript加載HTML模板
我有「templates.html」,其中包含我想加載到JavaScript並使用的HTML片段的集合。記住templates.html不是加載的DOM文檔,訪問模板/代碼片段的好方法是什麼?
我在想使用document.open
來創建一個DOM來訪問,但我認爲這在某些瀏覽器上有問題。
您可以將HTML加載到一個隱藏的div,然後你將有一個DOM訪問 使用jQuery的負載來加載HTML一個DIV最簡單的方法:http://api.jquery.com/load/
使用jQuery和(http://api.jquery.com/load/ )方法將加載的文檔注入到DOM中。
$(function() {
$('#content').load('/templates.html');
});
歡呼的示例代碼 – iancrowther
這是我的解決方案,只是不要忘記添加回調函數!因爲如果您要添加功能,可能內容尚未加載,所以最好等待它。 $('#content')。load('/ templates.html',function(){ //加載html時要做的事情 }); – epergo
另一種方法是使用requireJS。
require (['text!template_name'], function(yourTemplate) {
// do stuff in here with yourTemplate dinamically load
}
嗨安德烈,感謝您的答案,我沒有真正使用requirejs,但意識到這一點,現在我有一個理由鼓搗.. http://www.bennadel.com/blog/2285-Writing-A-RequireJS-插件加載遠程-jQuery-Templates.htm – iancrowther
你可以動態加載大量的東西,它非常有用。我用它來製作咖啡代碼和模板。 –
對於簡單的要求,你可以嘗試:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
//do something with xhr.responseText
}
};
xhr.open('GET', '/template.html');
xhr.send();
你可以加載模板異步使用jQuery AJAX
$.get("/html/template01.html")
.done((data) => {
console.info(data); // output the content of the html file
});
是否可以將該模板「template01.html」連接到沒有狀態的控制器(在controller.js(Ionic/Cordova應用程序)中定義)? –
這是一個有點老,但因爲「用JavaScript加載HTML模板「現在應該指的是加載一個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>
或者動態創建它們。
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)
因爲我們想要的模板的內容根據一些文本,我們從網絡得到建立,我們必須分析它,並把它添加到我們的template.content
。
const text = fetchTemplateSomehowAsText('my-template.html')
const parsedDocument = new DOMParser().parseFromString(text, 'text/html')
template.content.append(parsedDocument.querySelector('#my-snippet'))
如果my-template.html
已經自帶裹在<template>
標籤我們能夠避免手動創建模板元素的一部分,因爲在已經的DOMParser爲我們創建模板元素。
document.head.append(
new DOMParser().parseFromString(text, 'text/html')
.querySelector('template')
)
)
This是我一直使用到的模板裝入文件片斷動態地使用我剛纔解釋。
謝謝, 這完全按照需要的技巧。 Ian – iancrowther
一些示例代碼總是很好。這就是爲什麼我更喜歡peterp的回答 –