四、事件
先写了一个小项目: 简单计算器
代码如下:
<!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>计算器小项目</title>
<style>
button {
width: 100px;
height: 100px;
color: white;
background-color: green;
font-size: 80px;
}
button:active {
color: green;
background-color: white;
}
div {
text-align: center;
}
input.ansbox {
width: 302px;
height: 89px;
background-color: antiquewhite;
color: black;
font-size: 40px;
padding: 0px 2px;
margin-bottom: 0px;
text-align: right;
}
</style>
</head>
<body>
<script>
var num1 = 0,
op = '',
new_turn = false
function show_input(a) {
var inp = document.getElementsByTagName('input')[0]
now = inp.value
if (new_turn) {
now = '0'
new_turn = false
}
if (a != '.') {
if (now.length === 1 && 1 * now === 0) {
next_show = a
} else {
next_show = now + a
}
} else {
if (('' + now).indexOf('.') == -1) {
console.log(now)
next_show = now + a
}
}
inp.value = next_show
}
function del_fn() {
var inp = document.getElementsByTagName('input')[0]
now_show = inp.value
if (now_show.length > 1) {
inp.value = now_show.slice(0, -1)
} else {
inp.value = 0
}
}
function op_fn(temp) {
op = temp
var inp = document.getElementsByTagName('input')[0]
num1 = inp.value
inp.value = 0
}
function calculate() {
var inp = document.getElementsByTagName('input')[0]
num2 = inp.value
console.log(op)
if (op === '+') {
result = 1 * num1 + 1 * num2
} else if (op === '-') {
result = num1 - num2
} else if (op === '*') {
result = num1 * num2
} else if (op === '/') {
if (1 * num2 === 0) {
result = '0'
} else {
result = num1 / num2
}
} else if (op === '') {
result = num2
}
num1 = 0
op = ''
new_turn = true
inp.value = result
}
</script>
<div>
<input class="ansbox" value="0" readonly />
<button
style="font-size: 30px; height: 100px; margin: 0px"
onclick="del_fn()"
>
del</button
><br />
<button onclick="show_input(1)">1</button>
<button onclick="show_input(2)">2</button>
<button onclick="show_input(3)">3</button>
<button onclick="op_fn('+')">+</button><br />
<button onclick="show_input(4)">4</button>
<button onclick="show_input(5)">5</button>
<button onclick="show_input(6)">6</button>
<button onclick="op_fn('-')">-</button><br />
<button onclick="show_input(7)">7</button>
<button onclick="show_input(8)">8</button>
<button onclick="show_input(9)">9</button>
<button onclick="op_fn('*')">X</button><br />
<button onclick="show_input('.')">.</button>
<button onclick="show_input(0)">0</button>
<button onclick="op_fn('/')">/</button>
<button onclick="calculate()">=</button><br />
</div>
</body>
</html>
顺序执行时,标签可能未解析到(定时器小样例)
<script>
var now = new Date()
var h = document.getElementsByTagName("h1")[1]
console.log(h)
</script>
<h1>当前系统时间为:</h1>
<h1></h1>
系统输出:undefined。这是因为在执行script
标签时,h1
标签还未解析到。改为:
window.onload = function () {
var now = new Date()
var h = document.getElementsByTagName("h1")[1]
h.innerHTML = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + " " + now.getHours() + ":" + now.getMinutes
() + ":" + now.getSeconds();
}
为了刷新时间,使用函数setInterval
,加上下面的代码:
var d = setInterval(showTime, 1000); // 设置每1000ms执行一次,参数: (函数对象,间隔时间)
如果,想要一段时间计时后停止,则使用函数setTimeout
:
var t = setTimeout(function () {
clearInterval(d); // 参数: (函数对象,间隔时间)
}, 6000)
至此,一个定时器就完成了。
五.数组
定义和简单遍历
var arr = []
var arr2 = [1, 2, 3, 4]
for (var i = 0; i < arr2.length; i++) {
document.write(arr2[i], ',') // 输出: 1,2,3,4,
}
for-in
的变量是下标:
for (var i in arr2) {
document.write(i, ":", arr2[i], ";") // 输出: 0:1;1:2;2:3;3:4;
}
它俩有一些区别: for-in
会过滤掉undefined
,但前者不会
var arr3 = [1, , 2, , 3, , 4, null]
for (var i = 0; i < arr3.length; i++) {
document.write(arr3[i], ',')
}
document.write('<br>')
// for-in: 不输出 undefined ,但是索引暴露了它们
for (var i in arr3) {
document.write(i, ':', arr3[i], '<br>')
}
document.write('<hr>')
方法Array.for-Each()
,和Object.keys()
// 每个数组元素都迭代一次函数对象
arr2.forEach(function () {
document.write(0, ',') // 0,0,0,0,
})
// 函数对象的参数可以写1个,也可以2个,3个,意思固定为:
// 元素值,元素索引,数组本身
arr2.forEach(function (value, index, array) {
document.write('value : ', value) //
document.write('index : ', index)
document.write('array : ', array.toString(), '<br>')
})
但其实,参数完整形式是:(函数对象[,thisValue])
thisValue是可选的(若传递则为this
,否则是undefined
)
arr2.forEach(function () { document.write(this) })
// [object Window][object Window][object Window][object Window]
document.write("<br>")
arr2.forEach(function () { document.write(this) }, obj)
// [object Object][object Object][object Object][object Object]
document.write("<br>")
// Object.keys(),获取索引. 也可以获取数组的索引,但没必要.
document.write(Object.keys(obj)) // name,age,gender
document.write('<hr>') // 划出分割线
Object.keys()
,获取索引.它可以得到字典的key值
数组的栈操作,push(),pop()
// 生成 10 个 0~100 内的随机数
var stack = []
for (var i = 0; i < 10; i++) {
// var rdn = Math.floor(Math.random()*100)
var rdn = parseInt(Math.random() * 100)
stack.push(rdn)
}
document.write('数组内容是: ', stack.toString(), '<br>')
// 数组内容是: 32,43,53,68,71,23,93,49,84,49
document.write('逆序输出一下: ', '<br>')
while (stack.length) {
document.write(stack.pop(), ',')
}
// 输出: 49,84,49,93,23,71,68,53,43,32,
document.write('<hr>')
删除元素
delete()
会把元素删除,但是,用undefined
代替
var arr = [1, 2, 3, 4, 5]
delete arr[3]
document.write('arr: ', arr, ',arr[3]:', arr[3])
// arr: 1,2,3,,5,arr[3]:undefined
直接指定arr2.length
document.write('<br>')
var arr2 = [1, 2, 3, 4, 5]
arr2.length = 3
document.write('arr2: ', arr2) // arr2: 1,2,3
.splice(pos,num)
,从pos位置起,删除num个
var arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr3.splice(2, 1) // 删除第2个位置的元素
document.write(arr3, '<br>') // 1,2,4,5,6,7,8,9
var arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr3.splice(2, 3) // 删除第2个位置的3个元素
document.write(arr3, '<br>') // 1,2,6,7,8,9
删除后补充元素
.splice(pos,num,待补充的元素)
arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr3.splice(2, 3, 0, 0, 0, 0) // 1,2,0,0,0,0,6,7,8,9
document.write(arr3, '<br>')