gpt4 book ai didi

Javascript setAttribute 无法正常工作

转载 作者:行者123 更新时间:2023-11-28 14:34:07 25 4
gpt4 key购买 nike

我正在尝试实现 w3schools 提供的 includeHTML() 函数。

https://www.w3schools.com/howto/howto_html_include.asp

如果我手动创建一个 div,它可以正常工作,就像在网站中一样:

<div w3-include-html="awebsite.html"></div>

但是,如果我尝试使用 Javascript 创建 div,则它不起作用,例如:

var htmlIncluder = document.createElement("div");
htmlIncluder.setAttribute("w3-include-html", "awebsite.html");
document.body.appendChild(htmlIncluder);

是不是因为div默认没有w3-include-html属性?我应该做什么才能使这项工作成功?

感谢您的帮助!

更新,这是我的index.html,为了更清楚事物出现的顺序,它还显示了includeHTML函数:

<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>
</head>
<body>
<!--this is the manually created div that works-->
<div w3-include-html="2.html"></div>
<!-- divs created with js.js have the correct attribute but don't show any content -->
<script src="js.js"></script>
<script>
includeHTML();
</script>
</body>

这是 js.js 创建应包含 includeHTML() 的 div 的部分;内容。 div 被添加到添加到网格的单元格中,并且整个内容被添加到 document.body 中。它在网站中可见,因此它是正确的,例如文本元素“middle”是可见的。页面以网格形式分为页眉、中间和页脚,所有这些也是可见的。

cell.className = "middle";
cell.id = "middle-"+cellIdNo;
var text = document.createTextNode("middle");
var htmlIncluder = document.createElement("div");
htmlIncluder.setAttribute("w3-include-html", "2.html");
cell.appendChild(text);
cell.appendChild(htmlIncluder);

最佳答案

尝试用document.body代替cbody

var htmlIncluder = document.createElement("div");
var t = document.createTextNode("test"); // only for testing
htmlIncluder.appendChild(t); // only for testing
htmlIncluder.setAttribute("w3-include-html", "awebsite.html");
document.body.appendChild(htmlIncluder);

关于Javascript setAttribute 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com