Javascript onload事件未在对象内部激发
Javascript onload event not firing inside object
我正试图弄清楚为什么这不起作用,并想知道是否有人能帮我。基本上,我需要具有不同图像的该对象的多个实例,并且我需要每个对象存储其关联图像的图像高度/宽度以供进一步操作,但是onload事件从未触发?
很抱歉,伙计们要清楚完整的代码,如果你看到TestTheVar函数imgW从未被设置为任何东西。
<script type="text/javascript">
(function() {
var myTest = new TestObj();
mytest.TestTheVar();
})();
function TestObj() {
this.img = new Image();
this.img.onload = function(){
this.imgW = this.img.width;
this.imgH = this.img.height;
};
this.img.src = "reel_normal.PNG";
this.TestTheVar = function() {
alert(this.imgW);
}
}
</script>
这里有两个问题
1) 范围
2) 定时
其他答案中提到的范围是指onload函数中的this
是Image
对象,而不是您的TestObj,因此您需要执行以下操作:
<script type="text/javascript">
(function() {
var myTest = new TestObj();
mytest.TestTheVar();
})();
function TestObj() {
var self = this;
this.img = new Image();
this.img.onload = function(){
self.imgW = this.width;
self.imgH = this.height;
};
this.img.src = "reel_normal.PNG";
this.TestTheVar = function() {
alert(this.imgW);
}
}
</script>
时间是指当您试图访问高度和宽度时,您不能假设图像已经完成加载。这就是回调的好处:
<script type="text/javascript">
(function() {
var myTest = new TestObj(function() {
myTest.TestTheVar();
});
})();
function TestObj(cb) {
cb = cb || function() {};
var self = this;
this.img = new Image();
this.img.onload = function(){
self.imgW = this.width;
self.imgH = this.height;
cb();
};
this.img.src = "reel_normal.PNG";
this.TestTheVar = function() {
alert(this.imgW);
}
}
</script>
this
是属于每个函数的关键字。
在load
事件侦听器中,它将是映像,而不是您的TestObj
实例。
因此,您可以
-
使用
this.img.imgW
获取:function TestObj() { var that = this; this.img = new Image(); this.img.onload = function(){ this.imgW = this.width; this.imgH = this.height; that.testTheVar(); }; this.img.src = "reel_normal.PNG"; this.testTheVar = function() { alert(this.img.imgW); }; }
-
将其存储在您的
TestObj
实例中:function TestObj() { var that = this; this.img = new Image(); this.img.onload = function(){ that.imgW = this.width; that.imgH = this.height; that.testTheVar(); }; this.img.src = "reel_normal.PNG"; this.testTheVar = function() { alert(this.imgW); }; }
-
将事件处理程序中的
this
自定义为TestObj
实例:function TestObj() { this.img = new Image(); this.img.onload = (function(){ this.imgW = this.img.width; this.imgH = this.img.height; this.testTheVar(); }).bind(this); this.img.src = "reel_normal.PNG"; this.testTheVar = function() { alert(this.imgW); }; }
相关文章:
- 如何使用内部对象构造对象
- 这个 getter-setter 闭包是否有充分的理由以这种方式在其内部对象中声明它是私有的
- 为什么这个内部对象文字等于另一个对象
- 内部对象如何在声明时引用其父对象的对象
- 将角度对象函数调用传播到内部对象
- Javascript 变量范围.如何从内部对象函数访问对象变量
- 更改此内部对象的行为
- "node-r包.json“-如何访问内部对象
- 在使用es2015时,我们应该如何获得对函数内部对象的引用
- 使用“;这个“;internal$.each内部对象方法
- '这'ES6中的内部对象文字
- 访问对象内部对象的属性
- 当数组是服务内部对象的属性时,如何在页面上逐个显示数组元素
- 用循环将内部对象附加到多维数组中
- 从内部对象javascript设置字段值
- 外部文件与内部对象的GeoJSON投影
- 如何在javascript对象中访问内部对象的属性
- 调用内部对象函数javascript
- Javascript函数内部对象的不同
- “this"内部对象