2014-06-15 24 views
4

我試圖安裝underscore.js,所以我可以在我的瀏覽器中使用它,但似乎所有的安裝說明都是針對服務器的。我如何在我的網頁瀏覽器中使用它?我知道JS has no import or require所以我不知道該怎麼做。謝謝如何安裝underscore.js?

+4

只包含腳本文件。 (或使用Require.js或Browserify) – SLaks

+0

我不知道如何做到這一點,說實話。具體來說,我在哪裏包括它?我假設我需要首先下載它,但我不知道要將其放置在什麼文件夾中。 –

+1

HTML中的'

0

你應該可以加載它使用<script>標記。看代碼顯示它會將自身加載到全局對象中(window == this)。

var root = this; 

    ... 

    if (typeof exports !== 'undefined') { 
    if (typeof module !== 'undefined' && module.exports) { 
     exports = module.exports = _; 
    } 
    exports._ = _; 
    } else { 
    root._ = _; 
    } 
3

你不安裝一個JavaScript庫,以便使用它 - 你需要包括它。如果你有依賴項,那麼只有順序(例如第一個underscore.js,然後是使用underscore.js的自定義庫)很重要。 一種可能性是使用一些Content Delivery Network (CDN),所以你不需要在本地下載庫。常見CDN的是:

如果你下載的庫並將其託管服務器上,不是僅僅把它放在你的項目目錄(或一個名爲腳本的目錄)。

,其中包括underscore.js自定義庫使用可能看起來像這樣庫的代碼:

JS庫demo.js

// function using underscore.js 
function demo() { 
    var input = [1, 2, 3]; 
    var output = _.map(input, function(item) { 
      return item * 2; 
    }); 
    alert(input + " - " + output); 
} 

,然後在第二個文件demo.html

<!DOCTYPE HTML> 
<html> 
    <head> 
     <!-- first include the underscore.js library --> 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js" type="text/javascript"></script> 
     <!-- or if the file is downloaded locally --> 
     <!-- <script src="scripts/underscore.js" type="text/javascript"></script>--> 
     <!-- then the custom JS library --> 
     <script src="demo.js" type="text/javascript"></script> 
    </head> 
    <body> 
     <!-- call the custom library function --> 
     <a href="#" onclick="demo();">Start the script using underscore.js</a> 
    </body> 
</html> 

輸出如期:

1,2,3 - 2,4,6 
2

只需將以下代碼粘貼到.html文件的頭部分即可。

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3 /underscore-min.js"> 
</script> 
6
  • 打開網頁的一些谷歌瀏覽器或Mozilla Firefox。例如,google.com。
  • 然後按F12鍵。
  • 選擇控制檯Tab.And類型或複製 - 粘貼以下代碼:

變種腳本=使用document.createElement( '腳本'); script.type ='text/javascript'; script.src ='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js'; document.head.appendChild(script);

並按Enter鍵。

然後開始在控制檯上輸入你的下劃線js命令。

如果您覺得此內容有幫助,請給我一個滿意的答覆。