[英]Getting script in .js file to load in HTML
I wrote a simple copyright script in javascript that I have tested to work correctly: 我用javascript写了一个简单的版权脚本,经测试可以正常工作:
<!DOCTYPE html> <html> <body> <p id="footer"></p> <script type = "text/javascript"> var initialYear = 2016; var currentYear = new Date().getFullYear(); var yearYext = "null " if (initialYear == currentYear) { yearText = " " + initialYear + " "; } if (initialYear != currentYear) { yearText = " " + initialYear + " - " + currentYear; } var copyright = { name : "Elliander Eldridge", symbol : '\©', year : yearText, }; document.getElementById("footer").innerHTML = "Copyright " + copyright.symbol + " " + copyright.year + " " + copyright.name + ". All rights reserved."; </script> </body> </html>
(as you can see from the run button) (从运行按钮可以看到)
So I moved the script portion into js/site.js (within the directory tree of the website files) and wanted to load this within the footer of all pages. 因此,我将脚本部分移至js / site.js(在网站文件的目录树内),并希望将其加载到所有页面的页脚中。
The problem is that using neither this: 问题是这两个都不使用:
<script src="../js/site.js"></script>
nor this: 也不是这样:
<script src="../js/site.js">
<p id="footer"></p>
</script>
Does anything at all, and I can't seem to find a way to get this to load at all. 根本没有做任何事情,而且我似乎根本找不到找到这种方法来加载的方法。 I also tried putting that in other parts of the page without success. 我也尝试将其放在页面的其他部分,但没有成功。 I even tried putting that in the css file that every page is supposed to load. 我什至尝试将其放在应该加载每个页面的css文件中。
As a side note, I'd like to be able to load more than one script from this file, similar to how I might use multiple css classes within one css file, but not sure how to go about doing this here. 附带说明一下,我希望能够从该文件中加载多个脚本,类似于我可能在一个css文件中使用多个css类的方式,但是不确定如何在此处执行此操作。
PS - Please don't advise me on alternate ways of writing this in javascript. PS-请不要建议我用JavaScript编写此文字的其他方法。 I just need help getting to load what I have already written. 我只需要帮助就可以加载已写的内容。
Your js code is called at the beginning, even before the HTML content is loaded and it tries to find footer
, which obviously doesnt exist on the page yet. 甚至在加载HTML内容之前,您的js代码就会在开始时被调用,并且它会尝试查找footer
,而footer
显然尚不存在于页面上。
All you need to do is call the js, once the DOM is ready ie the HTML is loaded 您只需要做的就是调用js,一旦DOM准备就绪即加载HTML
<p id="footer"></p>
...
...
// and at the end of the page
<script src="../js/site.js"> </script>
Another tip that may help. 另一个提示可能会有所帮助。 Put your js code around this : 将您的js代码放在这周围:
$(document).ready(function() {
//put your code here
});
Oh and also, this is incorrect 哦,这也是不正确的
<script src="../js/site.js">
<p id="footer"></p>
</script>
EDIT: 编辑:
Since you dont want to use jquery, do this : 由于您不想使用jquery,请执行以下操作:
document.addEventListener('DOMContentLoaded', function() {
// put your code here
}, false);
This makes sure that the javascript code runs only after the DOM is loaded 这样可以确保仅在加载DOM之后运行javascript代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.