2014-01-18 26 views
1

在下面的代碼中,當我從對象外部調用「some_function」時,它會提示零。 當我點擊「some_button」時,也會調用「some_function」,但在這種情況下它會提示未定義。 什麼問題?對象內部按鈕的點擊事件

some_object = { 
    some_variable: 0, 
    some_button: $('<input />', { 
     type: "button", 
     value: "Click Me" 
    }), 
    some_function: function() { 
     alert(this.some_variable); 
    }, 
    init: function() { 
     $("body").append(this.some_button); 
     this.some_button.click(this.some_function); // Result is undefined 
    } 
} 
some_object.init(); 
some_object.some_function(); // Result is 0 

回答

0
some_function: function() { 
    alert(this.some_variable); 
}, 

這指的是按鈕不是對象。 試試這個:

some_object = { 
some_variable: 0, 
some_button: $('<input />', { 
    type: "button", 
    value: "Click Me" 
}), 
some_function: function (variable) { 
    alert(variable); 
}, 
init: function() { 
    $("body").append(this.some_button); 
    $this = this; 
    $this.some_button.click(function(){ 
     $this.some_function($this.some_variable); 
    }); 
} 
} 
some_object.init(); 
some_object.some_function(some_object.some_variable); 
+0

some_object = { some_variable:1, some_button:$('',{ type:「button」, value:「Click Me」 }), some_function:function(){ alert(some_object.some_variable);初始化:function(){ $(「body」)。append(this.some_button); $ this = this; $ this.some_button.click(function(){ $ this.some_function(); }); } } some_object.init(); some_object.some_function(); –

0

這是因爲,當您註冊一個單擊處理程序,這是指一個按鈕元素,而不是對象。相反,您可以撥打電話:

alert(some_object.some_variable); 
0

在此聲明this.some_function中,'this'是指單擊的按鈕不是對象'some_object'。

我覺得你的說法應該是這樣的

this.some_button.click(some_object.some_function); 

代替

this.some_button.click(this.some_function); // Result is undefined 
0

長安您的代碼如下:

some_object = { 
self = this, 
some_variable: 0, 
some_button: $('<input />', { 
    type: "button", 
    value: "Click Me" 
}), 
some_function: function() { 
    alert(self.some_variable); 
}, 
init: function() { 
    $("body").append(self.some_button); 
    this.some_button.click(self.some_function); // Result is undefined 
} 
} 
some_object.init(); 
some_object.some_function(); // Result is 0