2022/8/18
学习进度
JS(1) 完结
JS 的 引入方式
有三种方法
y总 提出 JS 可以在 html 代码任意位置出现 , 但由于页面是从上往下渲染的 , JS 一般放在 html 和 css 的后面
① :
<script type="module"></script>
type = "module" 不能省 , 这个 type 保证了在 <script> 的变量只有在 这个<scipt> 的作用域 , 而不是全局作用域
举例 :
<script type="module">
let x = 10;
console.log(x);
</script>
② :
在代码放在 .js 文件 , 在 <script> 中直接引用即可
举例:
<script type="module" src="/static/js/index.js"> </script>
③ :
export 和 import 的使用
在 .js 文件中
let x = 3 , y = 4;
function main(){
console.log("Hello World");
}
export {
x,
main
}
/意思是在外面可以用 import 引入 x 变量 和 main 函数/
在 html 代码中
<script type="module">
import { x, main } from "/static/js/index.js";
<!--注意一定要有 {} 括号 -->
console.log(x);
main();
</script>
对像
类似于 c++ 的 map
举例 :
<script type="module">
let d = {
name: "xqy",
age: 19
};
console.log(d.age);
</script>
注意格式是 let d = {}; ( 注意分号 ) , 且对象的每一个元素用","隔开 , 最后一个元素不用
d.age 和 d["age"] 是等价的 ,
但我们可以 let x = "age" , 再 d[x] , 这样 x 可作为一个变量.
课堂交互例子
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>
<link rel="stylesheet" href="/static/css/index.css">
</head>
<body>
输入
<br>
<textarea class="input" name="" id="" cols="30" rows="10"></textarea>
<br>
<button>Run</button>
<br>
<pre></pre>
<script type="module">
import { main } from "/static/js/index.js";
main();
</script>
/js 最好写 html 和 css 的后面/
</body>
</html>
js
let input = document.querySelector(".input");
/要有双引号 , 这里引入函数库的概念 , document.querySelector 查询第一个 input /
let run = document.querySelector("button");
let output = document.querySelector("pre");
function main() {
run.addEventListener("click", function () {
/当出现点击时 , 进行 function 函数 ,这里体现 js 的事件触发/
let s = input.value;
/textarea.value 获取 textarea 的输入/
output.innerHTML = s;
/ innerHTML 表示标签内部HTML的内容 /
})
}
export {
main
}
小细节补充
string 不分 单引号 和 双引号
等于是 "===" , 不等 "!=="
js 一般乘除按浮点数处理 , 如果想按整数 , 用到 parseInt()
举例:
<script type="module">
console.log(parseInt(5 / 3));
</script>
不等不是!== ???
写错了