javascript文件写在哪

本文详细介绍了JavaScript的四种常见书写位置:行内、内部script、外部文件和执行顺序,强调了结构与行为分离的重要性及推荐实践方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 二、 js写在哪

1. 行内:标签的行为属性内(如onclick,ondblclick,onmousedown,...)

- 不会自动执行,必须通过行为触发

- 结构和行为没有分离,不方便标签之间功能的复用和维护(不建议使用)

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style>

.box {

height: 100px;width: 100px;background-color: pink;

}

</style>

</head>

<body>

<!-- 点击盒子触发事件 -->

<div class="box" onclick="alert('hello world')"></div>

</body>

</html>

```

2. 内部:script标签内

- 可以不需要通过行为触发,会自动执行

- 结构和行为没有完全分离,不方便多个页面之间功能的复用和维护

- 优先写在body下方,且body的外部,html内部

```html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

.box{width: 100px;height: 100px;background: pink;}

</style>

</head>

<body>

<div class="box"></div>

</body>

<script>

alert('你好,世界')

</script>

</html>

```

3. 外部:js文件内,在html中使用script标签的src属性引入

- 可以不需要通过行为触发,会自动执行

- 结构和行为分离,方便功能的复用和维护(建议使用)

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style>

.box {

height: 100px;width: 100px;background-color: pink;

}

</style>

</head>

<body>

<div class="box"></div>

</body>

<!-- 结构和样式相分离,src引出文件所在路径 -->

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

</html>

```

4. 执行顺序

- 先写的先执行,后写的后执行,需要行为触发的,必须在行为触发后才行为

5. 注意

- 错误写法:既有内部又有外部时,合二为一,只使用一个script标签,大错特错!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草率怪199888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值