2013-03-03 78 views
0

我需要你的幫助。 如何在名稱空間中使用變量? 事情是這樣的:jQuery:命名空間,在另一個使用變量

所有的
$.MyScript = { 
    script: $("script") 
    , dataID: script.data("id") 
    , dataColor: script.data("color") 
    , Alerting: function alerting(){ 
     alert(dataColor); 
    } 
} 
$.Myscript.Alerting; 

回答

1

首先,這不是寫一個jQuery插件,以正確的方式,如果這就是你正在嘗試做的。請諮詢jQuery's Plugins/Authoring docs以瞭解正確的方法。


除此之外,你的代碼的方式,現在您可以通過關鍵字this引用父對象訪問dataColor

我從我的答案中刪除了代碼,因爲您還有其他問題。查看@ dfsq的答案,以解決您的問題。

我只是將我的答案留在這裏作爲官方文檔的參考。

1

在創建對象之前,您無法訪問script屬性。你可以使用這種模式,而不是:

$.MyScript = (function() { 

    var $script = $("script"); 

    return { 
     script: $script, 
     dataID: $script.data("id"), 
     dataColor: $script.data("color"), 
     alerting: function alerting() { 
      alert(this.dataColor); 
     } 
    } 
})(); 

$.MyScript.alerting(); 
+0

好的,謝謝你dfsq – 2013-03-03 10:08:11

+0

@JohnSmit標記您的提問。[接受這個答案](http://meta.stackexchange.com/a/5235/165614)作爲解決你的問題的解決。只需點擊該答案左上方的勾號(在投票下面)。 – Shef 2013-03-03 10:13:45

1

我建議你一個更通用的方法,而不涉及jQuery。 您可以隨時創建自己的名稱空間並對其進行擴展。

閱讀this beautiful article by Addy Osmani瞭解更多詳情。

相關問題