我正在尝试安装underscore.js,以便在浏览器中使用它,但似乎所有的安装说明都是针对服务器的。如何在我的网页浏览器中使用这个?我知道JS没有导入或要求,所以我不知道该怎么做。谢谢
发布于 2014-06-15 19:01:12
请包括您正在使用的浏览器,但是很少会想到:
- `Firefox`, install addon like `Firebug`, open a simple page like one of SO or google.com and in the console var script = document.createElement("script"); script.src = "http://path/to/underscor.js"; document.body.appendChild(script);
然后,您可以开始在JS文件中使用函数。
- Google Chrome,单击F-12,转到“源”选项卡,单击左侧面板中的“内容脚本”,右键单击“添加包含JS文件的文件夹”。这也应该有效。在左侧面板中还有另一个名为snippets的子选项卡,创建一个新文件并将整个JS文件复制到其中。或者,您也可以对Firefox采用相同的技术。它的开发者小组( Developer )更加先进和成熟。
要点是,您需要某种HTML来调用和使用JS代码。IMHO,像JSFiddle这样的工具在使用和测试一些JS代码方面要好得多,涉及的麻烦也较少。或者在您的系统上创建一个简单的HTML文件,包括一个脚本标记并测试它。
HTH
发布于 2016-04-21 11:03:09
var script = document.createElement('script');script.type = 'text/javascript';script.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js';document.head.appendChild(脚本);
然后按回车。
然后开始在控制台上键入下划线js命令。
发布于 2014-06-15 19:14:25
安装JavaScript库并不是为了使用它--您需要包含它。如果您有依赖项,那么只有顺序(例如,首先是underscore.js,然后是使用underscore.js的自定义库)才是重要的。一种可能是使用一些http://en.wikipedia.org/wiki/Content_delivery_network,这样您就不需要在本地下载库了。常见的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,6https://stackoverflow.com/questions/24232725
复制相似问题