2011-06-29 65 views
1

我创建一个Javascript对象,像这样:如何通过属性的onclick方法引用JavaScript对象?

function pager(elementId) { 
    this.totalPages = 5; 
    this.currentPage = 1; 

    var nextPageImage = document.createElement("img"); 
    nextPageImage.src = "img/next.png"; 

    nextPageImage.onclick = function(){ 
     if (this.currentPage+1 <= this.totalPages) 
     { 
      this.currentPage +=1; 
     } 
    } 

    document.getElementById(elementId).appendChild(nextPageImage); 
} 

我通过传递div的页面上的ID创建对象的一个​​实例:

myPager = new pager('pagerDiv'); 

的问题是,'这'onclick函数内部是指图像本身,而不是寻呼机对象。我可以通过使用'myPager'来引用传呼机目标,但这不太实际。

如何从图像onclick函数内引用对象?

回答

3

创建它代表一个局部变量“这个”,然后使用:

function pager(elementId) { 
    this.totalPages = 5; 
    this.currentPage = 1; 
    var th = this; 

    var nextPageImage = document.createElement("img"); 
    nextPageImage.src = "img/next.png"; 

    nextPageImage.onclick = function(){ 
     if (th.currentPage+1 <= th.totalPages) 
     { 
      th.currentPage +=1; 
     } 
    } 

    document.getElementById(elementId).appendChild(nextPageImage); 
} 
相关问题