jQuery上的事件处理
jQuery上的事件处理,jquery,event-handling,keypress,Jquery,Event Handling,Keypress,警报从未发生过。如果我将$(此)更改为#hero。它起作用了。我不明白为什么 function Car(id) { var $this = this; this.init = function() { this.el = document.getElementById(id); $(this).on('keypress', function(e){ alert(e.target); }); } }
警报
从未发生过。如果我将$(此)
更改为#hero
。它起作用了。我不明白为什么
function Car(id) {
var $this = this;
this.init = function() {
this.el = document.getElementById(id);
$(this).on('keypress', function(e){
alert(e.target);
});
}
}
元素显然是
this.el
,而this
是父init()
函数:
$(document).ready(function(){
var hero = new Car("hero");
hero.init();
});
当然,这更像jQuery:
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();
});
元素显然是
this.el
,而this
是父init()
函数:
$(document).ready(function(){
var hero = new Car("hero");
hero.init();
});
当然,这更像jQuery:
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();
});
试试这个。
如果要将事件绑定到函数,请将其绑定到元素
this.init = function() {
$('#' + id).on('keypress', function(e) {
alert(e.target);
});
}
试试这个。
如果要将事件绑定到函数,请将其绑定到元素
this.init = function() {
$('#' + id).on('keypress', function(e) {
alert(e.target);
});
}
非常感谢。顺便说一句,我确实使用了$this,但我没有包含过多的代码:)谢谢!顺便说一句,我确实使用了$this,但我没有包含过多的代码:)