闭包循环得索引值
闭包的用途:存循环的索引值
window.onload = function(){
var aLi = document.getElementsByTagName('li');
闭包做私有变量计数器
闭包的用途:私有变量计数器
闭包做选项卡
给每个选项卡按钮添加点击事件:aBtn[i].onclick = function(){
遍历所有选项卡按钮:for(var j=0; j<aBtn.length; j++){
将每个选项卡按钮都设为灰色:aBtn[j].className = '';
将每个内容区都隐藏:aCon[j].className = '';
this代表当前点击的Button对象:this.className = 'cur';
当前点击的按钮对应的内容显示:aCon[i].className = 'active';
单体创建对象
调用属性:
alert(Tom.name);
alert(Tom.age);
调用方法:
Tom.showName();
构建函数
new的作用就相当于工厂模式中最开始创建了一个空对象,最后把对象返回
function Person(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);
}
}
原型模式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
Person.prototype.showName = function(){
alert(this.name);
}
Person.prototype.showAge = function(){
alert(this.age);
}
Person.prototype.showJob = function(){
alert(this.job);
}
}
var Lucy = new Person('lucy',18,'测试鼠');
先去自己的对象中找showName函数,再去构造函数的原型找
Lucy.showName = function(){
alert('我的名字是' + this.name);
}
//重写自身对象中的方法,不会影响其它对象
call和apply的区别
二者都可以改变当前的this,区别在于apply方法要将参数放入数组中再传参二者都可以改变当前的this,区别在于apply方法要将参数放入数组中再传参
//父类
function Fclass(name, age){
this.name = name;
this.age = age;
}
Fclass.prototype.showName = function(){
alert(this.name);
}
Fclass.prototype.showAge = function(){
alert(this.age);
}
//子类
function Sclass(name, age, job){
//属性用call或者apply的方式来继承
Fclass.call(this, name, age);
this.job = job;
}
//方法继承:将父类的一个实例赋值给子类的原型属性
Sclass.prototype = new Fclass();
Sclass.prototype.showJob = function(){
alert(this.job);
}
//由于已经继承了父类的属性和方法,所以可以直接调用
var Driver = new Sclass('tom',18,'老司机');
Driver.showName();
Driver.showAge();
Driver.showJob();
新增选择器
//如果要选择多个元素用querySelectorAll
var aLi = document.querySelectorAll('.list li');
alert(aLi.length);
jQuery加载
JS写法
window.onload = function(){
var oDiv = document.getElementById('div');
alert(oDiv.innerHTML);//这是一个div元素
}
//jQuery的完整写法
//比上面JS写法先弹出,因为window.onload是把页面元素加载、渲染完才弹出,而ready()是把所有页面的节点加载完之后就弹出了,不用等渲染了
*$(document).ready(function(){
var $div = $('#div');
alert('jQuery:' + $div.html());//jQuery:这是一个div元素
})*
简写方式
$(function(){
var $div = $('#div');//CSS样式怎么写,这里就怎么写
//html()方法相当于原生JS的innerHTML
alert($div.html() + 'jQuery');
})
jQuery选择器
选择元素的规则和css样式相同
选择集转移
修改#div1的下一个元素的样式
$('#div1').next().css({color: 'red'});
修改#div1的下面所有p标签设置样式
$('#div1').nextAll('p').css({color: 'red'});
eq(2)是选择索引等于2的第三个li,siblings()表示除第三个之外的其它兄弟li
$('.list2 li:eq(2)').css({background:'gold'}).siblings().css({background:'green'});
find()是选择div内的class等于link1的元素
$('#div2').find('.link1').css({color:'red'});
$('.list li')与$('.list').children()的区别:
原始的选择集不一样
$('.list li')不能通过end()回到父级
$('.list').children()可以通过end()回到父级
jQuery样式操作
jQuery用同一个函数即可以取值、也可以赋值
读取样式
alert($('#div1').css('fontSize'));
设置(写入)样式
$('#div1').css({background:'gold'});
增加行间样式
$('#div1').addClass('big');
减少行间样式,多个样式用空格分开
$('#div1').removeClass('div2 big');