gpt4 book ai didi

javascript - HTML - w3-include-html 读取 javascript 问题

转载 作者:行者123 更新时间:2023-12-03 02:34:16 28 4
gpt4 key购买 nike

我正在使用 codepen.io 创建一个项目,在该项目中,我创建了两个 html 页面。第一个称为“header.html”,第二个称为“index.html”。我正在使用“w3-include-html”将 header.html 文件包含在 index.html 文件中。 header.html 文件使用外部 javascript 文件将日期时间返回到我创建的名为“时间”的特定 ID。问题是当我在我的index.html页面中时,标题被显示并且代码被运行,但是document.getElementById函数无法从index.html中使用的外部html页面找到id。

这是我的代码:

header.html

<html>
<head>
<script src="scripts/userInfo.js"></script>
</head>
<body>
<p id ="userName">username</p>
<p id ="time"></p>
<p id ="logcount">timeCounter</p>
<script>
dateTime();
</script>
</body>
</html>

index.html

<html>
<head>
<script src="https://www.w3schools.com/lib/w3.js"></script> <-used to
enable the use of the w3-include-html
</head>
<body>
<div w3-include-html="header.html"></div> <- refers to my html file and
places the assets on the page

<script>
w3.includeHTML(); <--to include the html file
</script>
<script src="scripts/userInfo.js"></script> <-- reference to javascript
file being used by header.html
</body>
</html>

userInfo.js

var sec =0;
var minute = 0;
var hour = 0;

var timeOutput;

function dateTime(){

var date = new Date();

var day = date.toDateString();

var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();


try{
document.getElementById("time").innerHTML = day + " " + hours + ":" +
minutes;
}catch(error){
alert(error); <- when run on the index.html page I get an error saying
that the id "time" could not be found. This does work when running just
on the header.html page.
}

setTimeout(dateTime,1000);
}

如有任何帮助,我们将不胜感激,谢谢。

最佳答案

这个 W3 Schools 脚本不是标准的,通过查看其源代码,它依赖于 XHLHttpRequest 对象 (AJAX)。仅当通过 HTTP 或 HTTPS 从服务器请求代码时,AJAX 请求才会起作用,因此在测试此代码时请确保您正在服务器上运行它。

此外,即使您可以正常工作,包含的文件也不应该是整个 HTML 文档。它应该只是您打算插入到更大文件中的片段。由于您尝试将 header.html 文件注入(inject)到 index.htmldiv 中,因此您应该只注入(inject)在内部有效的代码div,因此将 header.html 更改为:

<p id ="userName">username</p>
<p id ="time"></p>
<p id ="logcount">timeCounter</p>
<!-- You want the .js reference to come before your
attempt to use the code in the file and also
after any elements that the code will refer to. -->
<script src="scripts/userInfo.js"></script>
<script>dateTime();</script>

关于javascript - HTML - w3-include-html 读取 javascript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601626/

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