事件处理程序上的jquery“this”绑定问题(相当于原型中的bindAsEventListener)

时间:2010-05-19 09:49:05

标签: javascript jquery events binding this

在jquery中,事件hadler的绑定是生成DOM元素的事件(这指向dom元素)。 在原型中更改事件处理程序的绑定,可以使用bindAsEventListener函数; 如何从事件处理程序访问实例和DOM元素? 与How can I bind an event handler to an instance in JQuery?

类似
function Car(){
    this.km = 0;
    $("#sprint").click(this.drive); //setup event handler
}

// event handler
// in it I need to access both the clicked element
// and the binding object (instance of car)
Car.prototype.drive = function(){
    this.km += 10; // i'd like to access the binding (but jq changes it)
    this.css({ // also the element
        left: this.km 
    }); 
    // NOTE that is inside this function I want to access them not elsewhere
}

var car = new Car();

4 个答案:

答案 0 :(得分:4)

嗯,也许你可以使用jQuery.proxy()?

http://api.jquery.com/jQuery.proxy/

答案 1 :(得分:1)

只需将变量绑定到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
}

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

答案 2 :(得分:0)

否则指向的值this(即处理程序附加到的元素)也会在事件对象的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
}

答案 3 :(得分:0)

好的,你是:

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

我没有测试过它,但是应该是直接的,或者你出错的地方是你的“这个”,它正在看“sprint”元素而不是“car”对象。