2011-07-07 68 views
1

我有一個網頁鏈接的JavaScript對象:爲什麼我的錨不能觸發這個JavaScript對象?

//the constructor function 
function NewsScroller() { 

} 


//now put some config objects using the JSON structure 
NewsScroller.prototype.config = { 
    serviceUrl : '/NewsProvider.svc/rest/GetNews/', 
    pageIndex : 0 
} 


//the argumented constuctor for this object 
NewsScroller.prototype.init = function() { 


    this.getNews(this.config.pageIndex); 
    console.log(this.config.pageIndex); 

} 

NewsScroller.prototype.decreasePage = function() { 

    console.log('current page index ' + this.config.pageIndex); 

} 

然後我在頁面準備好聲明:

<script> 
     $(document).ready(function() { 

      var newsScrollerForPage = new NewsScroller(); 
      newsScrollerForPage.init(); 

      newsScrollerForPage.decreasePage(); 

     }); 

    </script> 

其產生的結果:

當前頁面的索引0

我想調用好玩的從一個錨標記ction所以我有:

<div class="scroller-left"> 
    <a id="scroller-left-a" href="javascript:newsScrollerForPage.decreasePage();"> 
     <img src="/Images/Left-Scroller.jpg"/> 
    </a> 
</div> 

但是當我點擊錨我得到:

newsScrollerForPage沒有定義

這是爲什麼?當然,我應該能夠像在.ready方法中那樣調用對象和函數?

回答

1

您在ready函數中使用局部作用域(通過使用「var」)定義newsScrollerForPage,除了在使用它的相同作用域中定義函數外,不能在其外部使用它(範圍從在哪裏定義函數,而不是從它們被調用的地方)。

您可以通過從之前取走var(使其更具全局性而非局部範圍)來快速解決問題,但我不建議將此作爲最佳解決方案。

更好地將錨連接起來,就像這樣:

$(document).ready(function() { 

     var newsScrollerForPage = new NewsScroller(); 
     newsScrollerForPage.init(); 

     newsScrollerForPage.decreasePage(); 

     document.getElementById("scroller-left-a").onclick=function() 
     { 
      newsScrollerForPage.decreasePage(); 
      return false; 
     } 

    }); 

和刪除HTML元素的HREF。

+0

我認爲,因爲封閉,那麼頁面將允許訪問該函數內的變量,即使它返回? – Exitos

+0

但是,你的權利只是關於這件事情是如何工作的?它只是一個可以訪問的函數嗎? – Exitos

+0

看到我關於範圍的編輯。 – ADW

相關問題