我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
当前回答
这是我的内联解决方案:
(() => { const includes = document.getElementsByTagName('include'); [] .forEach。调用(包含I => { let filePath = i.getAttribute('src'); fetch (filePath)。然后(file => { file.text()。然后(content => { i.insertAdjacentHTML(“afterend”、内容); i.remove (); }); }); }); }) (); FOO < p > < / p > <包括src = " a.html " >加载…< /包括> 酒吧< p > < / p > <包括src = " b.html " >加载…< /包括> < p > t < / p >
其他回答
不需要脚本。不需要做任何花哨的东西服务器端(尽管这可能是一个更好的选择)
<iframe src="/path/to/file.html" seamless></iframe>
由于旧的浏览器不支持无缝,你应该添加一些css来修复它:
iframe[seamless] {
border: none;
}
请记住,对于不支持无缝链接的浏览器,如果您单击iframe中的链接,它将使框架指向该url,而不是整个窗口。一种解决方法是让所有链接都有target="_parent",尽管浏览器的支持是“足够好”。
一个非常老的解决方案满足了我当时的需求,但下面是如何做到标准兼容的代码:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->
在我看来,最好的解决方案使用jQuery:
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p>This is my include file</p>
这个方法简单明了地解决了我的问题。
jQuery .load()文档在这里。
我还有一个解
在javascript中使用Ajax
以下是Github repo中的解释代码 https://github.com/dupinder/staticHTML-Include
基本思想是:
index . html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='main.js'></script>
</head>
<body>
<header></header>
<footer></footer>
</body>
</html>
main.js
fetch("./header.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./footer.html")
.then(response => {
return response.text()
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
这是我的内联解决方案:
(() => { const includes = document.getElementsByTagName('include'); [] .forEach。调用(包含I => { let filePath = i.getAttribute('src'); fetch (filePath)。然后(file => { file.text()。然后(content => { i.insertAdjacentHTML(“afterend”、内容); i.remove (); }); }); }); }) (); FOO < p > < / p > <包括src = " a.html " >加载…< /包括> 酒吧< p > < / p > <包括src = " b.html " >加载…< /包括> < p > t < / p >