0
function Car(id) {
    var $this = this;

    this.init = function() {
        this.el = document.getElementById(id);
        $(this).on('keypress', function(e){
            alert(e.target);
        });
    }
}

alert永远不会发生。如果我更改$(this)#hero. 有用。我不明白为什么。

$(document).ready(function(){
    var hero = new Car("hero");
    hero.init();
});
4

2 回答 2

3

元素显然是this.el,而thisinit()函数是:

function Car(id) {
    var $this = this; // you never use this ?

    this.init = function() {
        this.el = document.getElementById(id); // you set it to this.el
        $(this.el).on('keypress', function(e){ // so you should use that for the
            alert(e.target);                   // event handler as well
        });
    }
}

$(document).ready(function(){
    var hero = new Car("hero");
    hero.init();
});

小提琴

当然,这会更 jQuery'ish:

this.init = function() {
    $('#' + id).on('keypress', function(e) {
        alert(e.target);                   
    });
}
于 2013-09-15T18:29:42.250 回答
0

尝试这个。您将事件绑定到函数,将其绑定到元素。

function Car(id) {
    var $this = this;

    this.init = function() {
        this.el = document.getElementById(id);
        $(this.el).on('keypress', function(e){  //changed in this line
            alert(e.target);
        });
    }
}
于 2013-09-15T18:29:59.420 回答