代码之家  ›  专栏  ›  技术社区  ›  clyfe

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

  •  8
  • clyfe  · 技术社区  · 14 年前

    在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 回复  |  直到 14 年前
        1
  •  4
  •   acidtv    14 年前

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

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

        2
  •  1
  •   Sean Kinsey    14 年前

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

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

        3
  •  0
  •   Matti Virkkunen    14 年前

    价值 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
    }
    
        4
  •  0
  •   Val    14 年前

    好的,给你:

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

    我没有测试过它,但是应该是直接向前,或者说你哪里出错了,在你的“这个”上,它是在看“sprint”元素,而不是“car”对象。