整理之前自己学javascript时写的练手小例子发出来,以便偶尔来回顾一下
1、显示当前时间信息
function getTime() {
var now = new Date();
var outStr = "time is : " + now;
outStr += "
年:" + now.getFullYear();
//0~11, 0表示1月
outStr += "
月:" + now.getMonth();
outStr += "
日:" + now.getDate();
outStr += "
星期:" + now.getDay();
outStr += "
小时:" + now.getHours();
outStr += "
分钟:" + now.getMinutes();
outStr += "
秒:" + now.getSeconds();
//alert(outStr);
//document代表body里的内容,通过id得到time的div
document.getElementById("time").innerHTML = "" + outStr + "
";
}
function testDataType(){
//isNaN方法判断参数是否是非数值型
var boo = isNaN(3);//false
document.write("3 is word? : " + boo +"
");
boo = isNaN(3.14);//false
document.write("3.14 is word? : " + boo +"
");
boo = isNaN("string");//true
document.write("string is word? : " + boo +"
");
//parseFloat解析字符串返回第一个浮点数
document.write(parseFloat("21.4") +"
");//21.4
document.write(parseFloat("87 abc") +"
");//87
document.write(parseFloat("the 123") +"
");//NaN
//parseInt解析字符串返回第一个整数,第二个参数指定进制数
document.write(parseInt(18.95, 10) +"
"); //18
document.write(parseInt("12px", 10) +"
"); //12
document.write(parseInt("1110", 2) +"
")//14,返回二进制整数型
document.write(parseInt("hello") +"
"); //NaN
//数组
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var message = "";
//遍历数组
for(var i in days){
message += 'Day ' + i + ' is ' + days[i] + '
';
}
message += '
';
//遍历数组2
var array = [0,1,2,3,4,5,6,7,8,9];
var length = array.length;
for (var i=0; i < length; i++) {
message += array[i] + '-';
}
message += '
';
// 遍历数组3,最快
//var array = [0,1,2,3,4,5,6,7,8,9];
// for 循环
for (var i = array.length; i--;) {
message += array[i] + '-';
}
message += '
';
// 最快且优雅的代码,等价于遍历3
var array = [0,1,2,3,4,5,6,7,8,9];
// while 循环
var i = array.length;
while (i--) {
message += array[i] + "-";
}
document.write(message);
}
3、javascript对象,OOP
function testOOP(){
//创建一个对象
//方法1,普通赋值方法
objectOne = new Object();
objectOne.info = "i am one";
objectOne.showInfo = function(){
alert(this.info);
}
//方法2,构造方法
function ObjectTwo(){
this.info = "i am two";
this.showInfo = function (){
alert(this.info);
}
}
var objectTwo = new ObjectTwo();
//方法3, 使用JSON
var objectThree = {
"info" : "i am three",
"showInfo": function (){
alert(this.info);
}
}
//调用三个对象的方法
objectOne.showInfo();
objectTwo.showInfo();
objectThree.showInfo();
//使用prototype扩展对象
ObjectTwo.prototype.setInfo = function (info){
this.info = info;
}
objectTwo.setInfo("changed two");
objectTwo.showInfo();
//使用prototype继承对象
function Dog () {
this.name = "dog";
this.showName = function (){
alert("i am dog");
}
}
//继承ObjectTwo
Dog.prototype = new ObjectTwo();
var myDog = new Dog();
myDog.showName();
myDog.showInfo();
myDog.setInfo("i am changed dog");
myDog.showInfo();
//封装属性和方法
function Box(width, length, height){
//此处的属性和方法没有用this引用,所以属性name和方法volume是私有的,外部不准访问
name = "box";
function volume(a, b, c){
return a*b*c;
}
this.boxVolume = volume(width, length, height);
}
var b = new Box(10, 12, 15);
//alert(b.volume(10, 12, 15));//报错,因为方法是私有的
//只有这样才能访问volume
alert(b.boxVolume);
}
function testJSON(){
var user = '{"username" : "root", "password" : "1234"}';
var myObject = eval('(' + user + ')');//eval能执行任意的javascript代码,可能会导致不安全因素
alert(myObject.username);
alert(myObject["password"]);
//用parse直接解析字符串生成JSON对象
var myObject2 = JSON.parse(user);
alert(myObject2.username);
//JSON对象序列化成一组字符串
alert(JSON.stringify(myObject2));
}
//当页面载入的时候
window.onload = function(){
//为按钮添加响应onclick方法
//document.getElementById("add").onclick = testEvent2;
//document.getElementById("cancel").onclick = testEvent2;
document.getElementById("add").onclick = testEvent3;
document.getElementById("cancel").onclick = testEvent3;
}
//添加事件
//方法1,在标签中使用内联事件处理器,例
//步骤略
//方法2,document.getElementById("submit").onClick = function(){...},添加事件,设为null,取消事件
function testEvent2(){
//跨游览器获取event,事件对象
if(!e) var e = window.event;
//跨游览器获取发出事件的对象
var element = (e.target) ? e.target : e.srcElement;
if(element.id == "add")
document.getElementById("submit").onclick = clickButton;
else if(element.id == "cancel")
document.getElementById("submit").onclick = null;
}
//方法3,使用addEventListener为element添加事件,removeEventListener取消事件
function testEvent3(e){
//跨游览器获取event,事件对象
if(!e) var e = window.event;
//跨游览器获取发出事件的对象
var element = (e.target) ? e.target : e.srcElement;
var button = document.getElementById("submit");
var eventType = 'click';
if(element.id == "add")
addEventHandler(button, eventType,clickButton);
else if(element.id == "cancel")
removeEventHandler(button, eventType,clickButton);
}
//事件处理方法
function clickButton(e){
var text = document.getElementById("text");
if(text.value == "" || text.value == null){
alert("name not be null");
}else{
alert(text.value);
}
}
//跨游览器添加事件的方法
function addEventHandler(element, eventType, handlerFunction){
if(element.addEventListener){
//W3C
element.addEventListener(eventType, handlerFunction, false);
}else if(element.attachEvent){
//IE
element.addEventListener('on'+eventType, handlerFunction);
}
}
//跨游览器取消事件的方法
function removeEventHandler(element, eventType, handlerFunction){
if(element.removeEventListener){
//W3C
element.removeEventListener(eventType, handlerFunction, false);
}else if(element.detachEvent){
//IE
element.detachEvent('on'+eventType, handlerFunction);
}
}
function node(){
var ol = document.getElementById("toDoList");
//得到ol内的子节点
var list = ol.childNodes;
var count = 0;
for(var i=0; i < list.length; i++){
//nodeTpye==1,代表元素节点
if(list[i].nodeType == 1) count++;
}
alert("this list has " + count + " lines");
//getElementsByTagName,根据标签返回一个数组
var list2 = ol.getElementsByTagName("li");
alert("this list has " + list2.length + " lines");
//firstChild, lastChild,访问子节点列表第一个和最后一个
//麻烦的方法:var last = ol.childNodes[ol.childNodes.length - 1];
var last = ol.lastChild;
var first = ol.firstChild;
//nextSibling, previousSibling前一个和后一个兄弟节点
var mid = last.previousSibling;
var mid2 = first.nextSibling;
//nodeValue保存节点里的值
alert(mid.nodeValue == mid2.nodeValue);//true
var text = "";
for(var i=0; i < list.length; i++){
//nodeTpye==3,代表文本节点 包括空白
if(list[i].nodeType == 3) text += list[i].nodeValue;
}
alert(text);
//创建一个div
var newDiv = document.createElement("div");
//创建一个文本节点
var newTextNode = document.createTextNode("this is new TextNode");
//将文本节点添加到div里,作为div的子节点
newDiv.appendChild(newTextNode);
//克隆一个newDiv节点,布尔值参数表示是否复制所有子节点
var cloneDiv = newDiv.cloneNode(true);
//选择一个节点,把新的节点插入到它前面
cloneDiv.insertBefore(document.createTextNode("this is pre Text"), cloneDiv.firstChild);
alert(cloneDiv.childNodes[0].nodeValue + "\n" + cloneDiv.childNodes[1].nodeValue);
//删除一个子节点
cloneDiv.removeChild(cloneDiv.lastChild);
//用一个新节点代替旧节点
cloneDiv.replaceChild(document.createTextNode("replaced"), cloneDiv.firstChild);
alert(cloneDiv.childNodes[0].nodeValue);
//设置标签属性
ol.setAttribute("title", "new Title");
//动态添加javascript文件
var script = document.createElement("script");
script.setAttribute("src", "newScript.js");
document.head.appendChild(script);
}