闭包存循环索引
window.onload =function(){vara =document.getElementsByTagName("li");// alert(a.length)for(vari =0; i < a.length; i++) { (function(i){ a[i].onclick =function(){ alert(i) } })(i) } }//如果直接写不用闭包则结果会循环很快,结果只会是最后一个值
面向对象
单体创建对象
varTom = {name:'tom',age:18,showname:function(){ alert('我的名字叫'+this.name); },showage:function(){ alert('我今年'+this.age +'岁'); } } Tom.showage(); alert(Tom.age)
工厂模式
functionPerson(name, age, job){varo =newObject(); o.name = name; o.age = age; o.job = job; o.showname =function(){ alert('我的名字叫'+this.name); }; o.showage =function(){ alert('我今年'+this.age +'岁'); }; o.showjob =function(){ alert('我的工作是'+this.job); };returno;//必须有return}vartom = Person('tom',18,'程序员');//直接调用函数alert(tom.job) tom.showname();
构造函数
functionPerson(name, age, job){this.name = name;this.age = age;this.job = job;this.showName =function(){ alert(this.name) }this.showage =function(){ alert(this.age) }this.showjob =function(){ alert(this.job) }//不必须有return}varjack =newPerson("jack",22,"攻城狮");//实例化注意和面向对象中工厂的区别// var tom = new Person('tom', 22, '程序员');// jack.showjob()// alert(jack.name==tom.name)functionaa(a,b){ alert(this+" "+a+" "+b) } aa(1,2) aa.call("abf",1,2)//更改this值aa.apply("abf",[2,3])//更改this值
继承
functionFather(name, age){this.name = name;this.age = age; } Father.prototype.showname =function(){ alert(this.name) }; Father.prototype.showage =function(){ alert(this.age) };//子类functionSon(name, age, job){ Father.call(this, name, age);//属性继承this.job = job }//方法继承Son.prototype=newFather(); Son.prototype.showjob =function(){ alert(this.job) };varjack =newSon("jack",18,'程序猿'); jack.showname(); jack.showage(); jack.showjob();//不必须有return
jQuery部分选择器
$("#div1").next().css({//下一个元素color:'red'}) $("#div1").nextAll().css({//也可以选择特定的元素如:$("#div1").nextAll('p')background:'aqua'}) $("#span1").parent().css({width:'100px',backgroundColor:'red',fontSize:'30px'}) $("#two").closest('div').css({//祖先background:'gold'}) $(".list").children().css({background:'green'}) .end().css({background:'red'}) $(".list2 li:eq(2)").css({background:'black'}) .siblings().css({//选择同级兄弟元素background:'red'}) $(".div2").find("#link1").css({background:'gold'})
增删样式
// alert($(".box1").css('font-size'))$(".box1").css({background:'gold'}) $(".box1").addClass('big') $(".box1").removeClass('box1')
点击事件
$(function(){ $("#btn").click(function(){ $(".box1").toggleClass('sty')//切换样式}) })
获取索引值
$("#list li").click(function(){// alert(this.innerHTML)// alert($(this).html())//和上面一样都是获取值alert($(this).index())//获取索引值})