JS脚本应该放到HTML文件中去哪里? [英] Where should JS scripts go in an HTML file?

查看:91
本文介绍了JS脚本应该放到HTML文件中去哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有JS代码,它打算作为加载/构建页面的一部分来运行,那么在HTML中应该去哪里?例如修改< div> 或添加一些链接。
这应该放在< body> 中,散布HTML吗?或者它应该在< head> < body> 元素之间?按照什么顺序进行 - 它们在页面中的顺序或所有HTML都发生在哪里(非 - < head> )JS运行?

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a <div> or adding some links. Should this be put in the <body>, interspersed with HTML? Or should it be between the <head> and <body> elements? What order do things happen in - the order they are in the page or does HTML all happen before (non-<head>) JS is run?

推荐答案

整个HTML文件按写入的顺序执行,这意味着

The whole HTML file is executed in the order it is written, that means

<html>
  <div id="ID"></div>
  <script type="text/javascript">
    document.getElementById('ID').innerHTML = "HELLO";
  </script>
</html>

更改div的内容,其中

changes the contents of the div, wherease

<html>
  <script type="text/javascript">
    document.getElementById('ID').innerHTML = "HELLO";
  </script>
  <div id="ID"></div>
</html>

不会,因为JS代码是在div加载之前执行的。

does not, because the JS code is executed before the div has loaded.

编辑:如果你想让JS在页面加载后运行,使用window.onload或document.body.onload或者

If you want the JS to run after the page has loaded use window.onload or document.body.onload or

<body onload="...">

或者,如果您使用的是jQuery库等JS库,则可以使用

Alternatively if you're using a JS library such as jQuery, you can use

$(document).ready(function() {
  ...
});

这篇关于JS脚本应该放到HTML文件中去哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆