this指向及应用
来源:互联网 发布:淘宝网如何盈利模式 编辑:程序博客网 时间:2024/06/15 01:11
this:指的是调用当前方法(函数)的那个对象
this指向(常见情况):
function fn1(){
this
}
1>
fn1(); //this=>window
2>
oDiv.onclick =fn1; //this=>oDiv
3>
oDiv.onclick=function(){
fn1(); //fn1()里的this=>window
};
4>
oDiv.onclick=function(){
this //this=>oDiv
}
5>
<div onclick=" this "></div> //this=>div
6>
<div onclick="this fn1();"></div> //this=>window
this应用实例:
1>
window.onload=function(){
var aBtn = ducument.getElementsByTagName("input");
for(var i=0;i<aBtn.length;i++){
aBtn[i].onclick=function(){
this.style.background='yellow';//this=>aBtn,点击按钮变为黄色
};
}
};
如果把this换一个位置:
window.onload=function(){
var aBtn = ducument.getElementsByTagName("input");
for(var i=0;i<aBtn.length;i++){
aBtn[i].onclick=function(){
fn1();
};
}
function fn1(){
this //this=>window,并没有指向aBtn,所以写this.style.background='yellow';不会改变样式
}
};
解决方法:
我们写一个单词,并让他的值为空
var that = null;
aBtn[i].onclick=function(){
that=this
fn1();
}
调用fn1到时候找that
function fn1(){
that.style.background='yellow'; //实现效果
}
2>
window.onload=function(){
var aBtn = ducument.getElementsByTagName("input");
for(var i=0;i<aBtn.length;i++){
aBtn[i].onclick=fn1;
};
}
function fn1(){
this.style.background=''yellow; //this=>aBtn,因为在for循环中,fn1被aBtn调用了,点击按钮变为黄色
}
};
- this指向及应用
- this指向及this应用
- this指向详解及改变它的指向的方法
- js中的this指向问题及解决方案
- js函数作用域及this指向
- this指向
- this 指向
- this指向
- this指向
- this指向
- this指向
- this指向
- this指向
- this指向,改变this指向
- vue-cli快速构建项目>>>>及引入jquery、jquery插件、this的指向 mounted钩子函数应用
- 关于Javascript中this的指向以及一些应用
- 面试题:this指针的指向,以及call、apply应用
- 在原型链之中的查询及this指向问题
- 自写app与树莓派制作智能小车
- Linux网络管理
- Android 定位
- TP5 控制器间跳转传参
- Oracle密码过期及账户解锁的问题
- this指向及应用
- elasticsearch5.5.2手动创建索引并配置ik中文分词器
- map换算
- scrapy顺序执行多个爬虫
- 校级
- jboss与jersey依赖冲突问题解决
- 第二次考试前端
- 抽象类和接口
- ie8中textarea的编辑,滚动条等问题