this指向及应用

this:指的是调用当前方法(函数)的那个对象

this指向(常见情况):

 function fn1(){

this   

}

1>

fn1();    //this=>window

2>

oDiv.onclick =fn1;    //this=>oDiv

3>

oDiv.οnclick=function(){

      fn1();              //fn1()里的this=>window

};

4>

oDiv.οnclick=function(){

     this                 //this=>oDiv

}

5>

<div οnclick=" this "></div>   //this=>div

6>

<div οnclick="this fn1();"></div>    //this=>window

this应用实例:

1>

window.οnlοad=function(){

var aBtn = ducument.getElementsByTagName("input");

        for(var i=0;i<aBtn.length;i++){

aBtn[i].οnclick=function(){

        this.style.background='yellow';//this=>aBtn,点击按钮变为黄色

};

}

};

如果把this换一个位置:

window.οnlοad=function(){

var aBtn = ducument.getElementsByTagName("input");

        for(var i=0;i<aBtn.length;i++){

aBtn[i].οnclick=function(){

              fn1();

};

}

        function fn1(){

this    //this=>window,并没有指向aBtn,所以写this.style.background='yellow';不会改变样式

}

};

解决方法:

    我们写一个单词,并让他的值为空

    var that = null;


      找到当前按钮,并把this放到that里存起来:

       aBtn[i].οnclick=function(){

that=this

                fn1();

}

     调用fn1到时候找that

      function fn1(){

that.style.background='yellow';                 //实现效果

}

2>

window.οnlοad=function(){

var aBtn = ducument.getElementsByTagName("input");

        for(var i=0;i<aBtn.length;i++){

               aBtn[i].οnclick=fn1;

};

}

        function fn1(){

                 this.style.background=''yellow;    //this=>aBtn,因为在for循环中,fn1被aBtn调用了,点击按钮变为黄色

}

};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值