freeCodeCamp/guide/chinese/javascript/where-to/index.md

1.9 KiB
Raw Blame History

title localeTitle
Where to 去哪儿

去哪儿

JavaScript是HTML和Web的编程语言。在HTML中必须在<script>容器标记中插入JavaScript。


<script> 
  window.alert("This JavaScript Works!"); 
 </script> 

另外请记住您可以在HTML文档中放置任意数量的<script>标记。

<script>标签在哪里?

<script>标记可以放在<head><body>

<head> JavaScript

在此示例中JavaScript放在文档的<head>部分中。创建一个onClicked函数,在按下按钮时调用该函数。


<!DOCTYPE html> 
 <html> 
 <head> 
 <script> 
 function onClicked() { 
    window.alert("Hi, there!"); 
 } 
 </script> 
 </head> 
 
 <body> 
 
 <h1>JavaScript Testing</h1> 
 <button type="button" onclick="onClicked()">Try it</button> 
 
 </body> 
 </html> 

<body> JavaScript

这里JavaScript放在 。创建了onClicked函数,并将其设置为在单击按钮时触发。


<!DOCTYPE html> 
 <html> 
 <body> 
 
 <h1>JavaScript Testing</h1> 
 <button type="button" id="buttonClicked">Try it</button> 
 
 <script> 
 document.getElementById("buttonClicked").onclick = onClicked; 
 
 function onClicked() { 
    window.alert("Hi, there!"); 
 } 
 </script> 
 
 </body> 
 </html> 

外部脚本

脚本也可以放在外部文件中。让我们创建一个文件script.js

的script.js
window.alert("Hi!"); 

此脚本可以包含在HTML文档中如下所示


<!DOCTYPE html> 
 <html> 
 <body> 
 
 <script src="script.js"></script> 
 
 </body> 
 </html> 

_嗨_在呈现页面时仍会收到警报。请记住您不需要在JavaScript文件扩展名为**.js**的文件)中包含<script>标记。

更多信息:

雅虎建议在底部放置脚本。这阐述了这里 ,与这一建议的原因。