模块
参见 ES6 局部
DOM
参见 Web 相干局部
选择器
document.querySelector()
来获取网页的对应 HTML 元素document.querySelectorAll()
来获取网页的所有对应 HTML 元素document.getElementById()
依据 ID 获取元素document.getElementsByClassName()
依据类名获取元素document.getElementsByTagName()
依据 HTML 元素名获取元素
document.querySelector('p');
事件处理
监听事件的函数叫“事件监听器(event listener)”;处理事件的函数叫“事件处理器(event handler)”。
罕用的监听器:addEventListener()
,第一个参数是事件的类型,第二个参数是事件处理器。
const target = document.querySelector('body');function handleClick() { console.log('clicked the body');}target.addEventListener('click', handleClick);
也能够给 HTML 元素增加点击属性:
<h1 onClick='handleClick2()'></h1>function handleClick2() { console.log('clicked the heading');}
内容更新
能够应用 prompt()
内置办法获取用户输出。注:这不是最佳实际,应该应用表单。
let answer = prompt('What is your name?');if (typeof(answer) === 'string') { var h1 = document.createElement('h1') h1.innerText = answer; document.body.innerText = ''; document.body.appendChild(h1);}
var h1 = document.createElement('h1')h1.innerText = "Type into the input to make this text change"var input = document.createElement('input')input.setAttribute('type', 'text')document.body.innerText = '';document.body.appendChild(h1);document.body.appendChild(input);input.addEventListener('change', function() { h1.innerText = input.value})
数据格式
XML
XML(Extensive Markup Language)扩大标记语言是晚期罕用的数据传输文件格式。
XML 须要很多字符来形容传输的数据,并且是一门独立语言,不容易和 JS 互操作。
JSON
2001 年,Douglas Crockford 创造了 JavaScript Object Notation / JSON。
JSON 的劣势:
- 轻量级,语法相似 JS 的对象
- 容易用 JS 操作
除了作为数据传输格局外,JSON 还是一种文件格式,通常从第三方网站的 json
文件获取第三方数据。
规定
JSON 是一种格式化的字符串,以下规定是 JSON 数据或者从 JSON 中提取至 JS 对象中要恪守的:
根本类型:字符串,数组,布尔,null
- 字符串必须用双引号:"fruits"
- 数字用惯例 JS 语法示意:5,10,1.2
- 布尔值用惯例 JS 语法示意:
true
,false
- null 必须是
null
- 简单类型:对象,数组(没有函数!)
- 对象中所有键蕴含双引号
- 在 JSON 对象中和 JSON 数组中,值是逗号宰割的
- 不能应用 JS 正文
如果尝试字符串化不受 JSON 反对的数据,例如函数,操作会“无声地”失败。
如果尝试字符串化其余数据类型,例如 BigInt:123n,会失去如下谬误:Uncaught TypeError: Do not know how to serialize a BigInt.
一些非法的 JSON 实例:
'{ "color":"red", "nestedObject": { "color": "blue" } }' '["one", "two", "three"]''[{ "color": "blue" }, {"color: "red"}]'
JSON -> Object
应用 parse()
从 JSON 提取至 JS 对象:
const jsonStr = '{"greeting": "hello"}'JSON.parse(jsonStr); // {greeting: "hello"}
应用 JSON.stringify()
把对象转化为 JSON:
const data = { firstName: "John", lastName: "Doe", greeting: "Hello"}JSON.stringify(data) // '{"firstName": "John", "lastName": "Doe", "greeting": "Hello"}'