JS九

定时器

点击倒计时

html

1
2
3
4
<div class="box">
<input type="text"/>
<button>点击发送短信</button>
</div>

script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
window.onload = function(){
var btn = document.getElementsByTagName("button")[0];
var count = 5; //多少秒倒计时
var timer = null; // 定时器的名字
btn.onclick = function(){
clearInterval(timer); // 先清除掉原来的定时器
this.disabled = true; // this 指向的是 btn
var that = this; // 把 btn 对象 给 that
timer = setInterval(send,1000);
function send(){
// alert(this); // this 指向的是 定时器 window
// alert(that);
count--;
if(count >= 0){
that.innerHTML = '还有'+ count + "秒";
}
else {
that.innerHTML = "重新发送短信";
that.disabled = false;
clearInterval(timer); // 清除定时器
count = 5;
}
}
}
}

页面多少秒后跳转

html

1
<div id="demo"></div>

script

1
2
3
4
5
6
7
8
9
10
var demo = document.getElementById("demo");
var count = 5;
setInterval(fn,1000);
function fn(){
count--;
demo.innerHTML = "页面将在" + count + "后跳转";
if(count <= 0){
window.location.href = "http://www.baidu.com";
}
}

转换为字符串

1
2
3
4
var txt = 12345;
console.log(typeof (txt + "")); //string
console.log(typeof String(txt)); //string
console.log(typeof txt.toString()); //string

字符串常见操作方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var txt1 = "abcdefg"
var txt2 = "123456";
var txt3 = "一二三四五六"
var txt4 = " 123456 "
//返回指定索引位置的字符
console.log(txt1.charAt(3)); //d
console.log(txt2.charAt(3)); //4
console.log(txt3.charAt(3)); //四
//提取字符串的片断,并在新的字符串中返回被提取的部分
console.log(txt1.slice(1,4)); //bcd
console.log(txt2.slice(1,4)); //234
console.log(txt3.slice(1,4)); //二三四
//移除字符串首尾空白
console.log(txt4.trim());