Javascript jquery";这";事件处理程序上的绑定问题(相当于原型中的bindAsEventListener)

Javascript jquery";这";事件处理程序上的绑定问题(相当于原型中的bindAsEventListener),javascript,jquery,events,binding,this,Javascript,Jquery,Events,Binding,This,在jquery中,事件hadler的绑定是生成事件的DOM元素(它指向DOM元素)。 在prototype中,要更改事件处理程序的绑定,可以使用函数; 如何从事件处理程序访问实例和DOM元素? 近似 否则,此将指向的值(即处理程序附加到的元素)也将在事件对象的currentTarget属性中传递。因此,如果您使用前面提到的绑定函数: Car.prototype.drive = function(e) { // this will be your car object // e.c

在jquery中,事件hadler的绑定是生成事件的DOM元素(它指向DOM元素)。 在prototype中,要更改事件处理程序的绑定,可以使用函数; 如何从事件处理程序访问实例和DOM元素?
近似


否则,此将指向的值(即处理程序附加到的元素)也将在事件对象的
currentTarget
属性中传递。因此,如果您使用前面提到的绑定函数:

Car.prototype.drive = function(e) {
    // this will be your car object
    // e.currentTarget will be the element that you attached the click handler to
}
好的,给你:

var car = {km:0};
$("#sprint").click(function(){
    car.km += 10;
    $(this).css({ left: car.km });
});

我没有对它进行测试,但应该是直截了当的,因为你的“this”是在看“sprint”元素而不是“car”对象。只需将一个变量绑定到
this
并使用它即可

function Car(){
    this.km = 0;
    var that = this;
    $("#sprint").click(function(){
         that.drive(this);
    });
}


Car.prototype.drive = function(element){
    this.km += 10; // i'd like to access the binding (but jq changes it)
    this.css({ // also the element
        left: this.km 
    }); 
    alert(element.innerHTML);
    // NOTE that is inside this function I want to access them not elsewhere
}

处理程序将元素传递给实例

Hmm,也许您可以使用jQuery.proxy()


这正是我想要避免的:)我想这会自己解决:)但我更新了答案,说明了如何访问类实例和元素。另一个问题也有这样的答案,但我觉得很难看。这是jquery社区中建议的方法吗?一定有更好的。。。或者只是个人品味的问题。我会让它烤得更久,并且可能会接受你的答案。侦听器可能会收到一个
事件
对象,其中包含对触发事件的
元素的引用,你可能会使用它。但我不确定我觉得哪一个最丑。是的,但问题是我失去了对当前对象的引用(因为这个开关),我可以通过事件获取元素。currentTarget
this
绑定到范围,因此,为了让
这个
指向正确的作用域,您需要在“.”运算符的左侧有正确的对象,或者必须使用
.call
应用
将作用域应用于您希望调用的函数。不过,最简单的方法是通过引入一个作用域变量(如
that
)将正确的对象保留在左侧。我不能使用
bindAsEventListener
,因为它来自prototype。
function Car(){
    this.km = 0;
    var that = this;
    $("#sprint").click(function(){
         that.drive(this);
    });
}


Car.prototype.drive = function(element){
    this.km += 10; // i'd like to access the binding (but jq changes it)
    this.css({ // also the element
        left: this.km 
    }); 
    alert(element.innerHTML);
    // NOTE that is inside this function I want to access them not elsewhere
}