JavaScript代码在哪里放置?

In an HTML code, JavaScript can be placed at three places...

在HTML代码中,JavaScript可以放在三个位置...

  1. Between the <head>...</head> tag

    在<head> ... </ head>标记之间

  2. Between the <body>...</body> tag

    在<body> ... </ body>标记之间

  3. In the external file with an extension ".js"

    在扩展名为“ .js”的外部文件中

在<head> ... </ head>和<body> ... </ body>标记之间 (Between the <head>...</head> and <body>...</body> tags)

If we want to place a JavaScript code in an HTML file, we can place either in <head>...</head> tag or <body>...</body> tag.

如果要在HTML文件中放置JavaScript代码,则可以将其放置在<head> ... </ head>标记或<body> ... </ body>标记中。

Syntax:

句法:

<script type="text/javascript">
        //js code
</script>

Example:

例:

<html>
<head>
	<title>JavaScipt Example</title>
	<script type="text/javascript">
		//function to add two numbers
		function sum(a, b){
			return (a+b);
		}
	</script>
</head>

<body>
	<script type="text/javascript">
		//function to subtract two numbers
		function sub(a, b){
			return (a-b);
		}
	</script>
	<p>Here, we are printing sum & sum...</p>
	<p id="result1"></p>
	<p id="result2"></p>

	<script type="text/javascript">
		//calling functions & printing the values
		document.getElementById("result1").innerHTML = "sum = " + sum(10,20);
		document.getElementById("result2").innerHTML = "sub = " + sub(10,20);
	</script>	
</body>
</html>

Output:

输出:

Here, we are printing sum & sum...

sum = 30

sub = -10

在扩展名为“ .js”的外部文件中 (In the external file with an extension ".js")

We can also write JavaScript code in an external file, and import the file in an HTML file.

我们还可以在外部文件中编写JavaScript代码,并在HTML文件中导入文件。

Syntax to import JavaScript file in an HTML file:

在HTML文件中导入JavaScript文件的语法:

    <script src="file_name.js"></script>

Example:

例:

JavaScript file (functions.js)

JavaScript文件(functions.js)

//function to add two numbers
function sum(a, b){
	return (a+b);
}

//function to subtract two numbers
function sub(a, b){
	return (a-b);
}

HTML file

HTML文件

<html>
<head>
	<title>JavaScipt Example</title>
	<script src="functions.js"></script>
</head>

<body>
	<p>Here, we are printing sum & sum...</p>
	<p id="result1"></p>
	<p id="result2"></p>

	<script type="text/javascript">
		//calling functions & printing the values
		document.getElementById("result1").innerHTML = "sum = " + sum(10,20);
		document.getElementById("result2").innerHTML = "sub = " + sub(10,20);
	</script>	
</body>
</html>

Output:

输出:

Here, we are printing sum & sum...

sum = 30

sub = -10


翻译自: https://www.includehelp.com/code-snippets/where-to-place-javascript-code.aspx

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值