在我的對象的構造函數中,我創建了一些span標記,並且需要將它們引用到同一對象的方法中。將點擊事件綁定到類中的方法
這裏是我的代碼示例:
$(document).ready(function(){
var slider = new myObject("name");
});
function myObject(data){
this.name = data;
//Add a span tag, and the onclick must refer to the object's method
$("body").append("<span>Test</span>");
$("span").click(function(){
myMethod(); //I want to exec the method of the current object
});
this.myMethod = myMethod;
function myMethod(){
alert(this.name); //This show undefined
}
}
有了這個代碼調用該方法,但它不是一個參考對象(this.name顯示未定義) 我該如何解決呢?
非常感謝!
其因爲'this'將參照當前範圍(這將是觸發事件它即點擊) –