2014-06-15 29 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命令。

如果您觉得此内容有帮助,请给我一个满意的答复。