<div id="import" includeHTML="page.html"></div>
function getInclude() {
var x = document.getElementById("import").includeHTML; //returns 'undefined'
alert(x);
}
function modInclude() {
document.getElementById("import").includeHTML = "page2.html"; //does nothing and FF's console outputs nothing
}
我正在使用W3的导入HTML进行一个项目,我想使用Javascript更改导入的页面。没问题,我认为这与更改图像来源相同。
我尝试的语法不起作用。我做了一些调查,发现该属性本身返回"undefined",考虑到它像它应该的那样导入页面,这有点奇怪。
可能你可以使用:
document.getElementById("import").setAttribute("w3-include-html", "contentYouWant.html");
编辑:我采用了w3-html-include的w3文档,并添加了一个简单的片段,您可以检查以了解真正发生的事情。代码段仅更改属性和警报,以确保其已更改。奇怪的是:'D函数来自官方文档。
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<div id="inc" w3-include-html="page1.html"></div>
<script>
includeHTML();
alert("Includes: " + document.getElementById("inc").getAttribute("w3-include-html"));
document.getElementById("inc").setAttribute("w3-include-html", "page2.html");
alert("Includes: " + document.getElementById("inc").getAttribute("w3-include-html"));
</script>
干杯