- 三种添加JavaScript方法
1 在head或body标签中添加script标签,在两个script标签之间填写代码
2 添加外部JavaScript文件,在head或body标签添加JS链接外部样式表
3 使用行内脚本(不推荐)
- 举例
1 添加script标签
1.1 在head标签内添加script标签
<head>
<meta charset="utf-8" />
<meta name="keywords" content="fish, smelly, trout, shark">
<meta name="description" content="We shell the smelliest fish online, guranteed!">
<title>my first web page</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script>
alert("Yo, welcome to my website!");
</script>
<!...网页加载时弹出对话框...>
</head>
注意:在点击确定前,浏览器没有渲染网页内容;
1.2 在body标签内添加script标签
<body>
<!...省略其他代码...>
<script>
alert("Yo, welcome to my website!");
</script>
</body>
注意:背景网页已加载完毕,因为浏览器在本网页末尾的body标签遇到该脚本,浏览器在处理JS前就已完成网页加载;
习惯上将JS脚本添加在body标签底部,但不是每次都奏效 ;
2 添加外部脚本文件
在index.html文件中,
<head>
<meta charset="utf-8" />
<meta name="keywords" content="fish, smelly, trout, shark">
<meta name="description" content="We shell the smelliest fish online, guranteed!">
<title>my first web page</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="scripts/main.js"></script>
</head>
注意:也可将script标签添加在body标签中,显示效果与第一种方法相同;
将JS与script链接;将CSS与link链接;
在main.js文件中,
alert("Yo Wencheng, welcome to my website!");
3 添加行内脚本
在导航部分a标签内添加行内文本,当点击该链接时,先弹出警报,点击确定后再跳转到该链接;
<li><a onclick="alert('Yo Wencheng, welcome to my website!');" href="http://www.163.com" target="_blank">Link to Netease Web</a></li>
注意:需要将提示信息的双引号改成单引号,以免对onclick属性的双引号造成干扰;
对于行内脚本,适用于控制网页上的指定事件;