使用对象获取位置(x,y)-Javascript
此代码适用于:使用对象获取位置(x,y)-Javascript,javascript,object,position,Javascript,Object,Position,此代码适用于: var myElement = document.getElementById("red"); setInterval(function() { console.log("Left:" + myElement.offsetLeft + "px | Top:" + myElement.offsetTop + "px"); }, 1000); 这会每秒打印出位置(x,y) 但如果我尝试将其更改为使用对象: function Enemy(id){
var myElement = document.getElementById("red");
setInterval(function() {
console.log("Left:" + myElement.offsetLeft + "px | Top:" + myElement.offsetTop + "px");
}, 1000);
这会每秒打印出位置(x,y)
但如果我尝试将其更改为使用对象:
function Enemy(id){
this.id = getElementById(id);
this.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + this.id.offsetLeft + "px | Top:" + this.id.offsetTop + "px");
}, 1000);
}
}
$(document).ready(function(){
var enemy = new Enemy("red");
enemy.getCoordinates();
});
它不输出任何内容-我看不出我的错误在哪里。在
设置间隔
或设置超时
(或任何类似onclick的事件处理程序)中,此
变量引用全局对象。在窗口的浏览器中
在现代浏览器中,您可以执行以下操作:
setInterval((function() {
console.log("Left:" + that.id.offsetLeft + "px");
}).bind(this), 1000); // <------- bind
setInterval((函数(){
log(“左:“+that.id.offsetLeft+”px”);
}).绑定(这个),1000);// 问题是“this”的值在设置间隔内发生变化。解决方案是将其更改为:
function Enemy(id){
this.id = document.getElementById(id);
var self = this;
this.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + self.id.offsetLeft + "px | Top:" + self.id.offsetTop + "px");
}, 1000);
}
}
正如slebetman所说,“this”变量不是您所期望的。尝试将其保存在“that”变量中,该变量可以在不同的作用域中访问
function Enemy(id){
var that = this; // reference to 'this' that can be used in other scopes
that.id = document.getElementById(id);
that.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + that.id.offsetLeft + "px | Top:" + that.id.offsetTop + "px");
}, 1000);
}
return that;
}
getElementById
不是全局函数,请使用document.getElementById
您还需要限定document.getElementById()
。
function Enemy(id){
this.id = document.getElementById(id);
this.getCoordinates = function(){
var element = this.id;
setInterval(function() {
console.log("Left:" + element.offsetLeft + "px | Top:" + element.offsetTop + "px");
}, 1000);
}
}
$(document).ready(function(){
var enemy = new Enemy("red");
enemy.getCoordinates();
});