html-W3 include-html阅读JavaScript问题



我正在使用codepen.io创建一个项目,在该项目中,我创建了两个HTML页面。第一个称为" header.html",第二个是" index.html"。我正在使用" W3-Include-html"将我的header.html文件包括在我的index.html文件中。header.html文件使用外部JavaScript文件将日期时间返回到我创建的名为" Time"的特定ID。问题是当我在我的index.html页面中时,显示标题并运行代码。

这是我的代码:

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学校脚本不是标准,并且在查看其源代码后,它依赖于Xhlhttprequest对象(AJAX(。AJAX请求只有在通过HTTP或HTTPS请求代码时才能使用,因此请确保在测试此代码时,请确保您在服务器上运行它。

此外,即使您可以使用此功能,包含的文件也不应该是整个HTML文档。它应该只是您打算插入较大文件的片段。由于您正在尝试将header.html文件注入index.htmldiv,因此仅应在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>

最新更新