我下载了 sample-project对于 latest-release的 RequireJS
.他们的documentation implies加载的任何内容都被传递到关联函数的参数列表中(以相应的顺序)。
所以我决定试一试……但是好像行不通!
Firebug
(网络选项卡)显示jQuery
正在加载:所以RequireJS
显然成功地完成了这部分Firebug
(控制台选项卡)显示“$ 不是函数”
我的问题是:为什么没有填充别名?
我的代码看起来像:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/require.js" type="text/javascript"></script>
<script type="text/javascript">
require(["scripts/jQuery/Core/jquery-1.7.2.min"], function ($) {
// jQuery is not passed-into the function, so the alias fails!
$(function () {
var stop = "";
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
他们的样本看起来像:
//Inside scripts/main.js
require(["some/module", "a.js", "b.js"], function(someModule) {
//...
});
最佳答案
jQuery 应该通过特殊名称“jquery”加载,否则它不会注册自己(因为 jQuery 使用命名定义)。
// create an alias that points to proper file
require.config({
paths : {
jquery : "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min"
}
});
// require jquery usign the path config
require(["jquery"], function ($) {
console.log($);
});
这就是为什么命名定义被认为是一种反模式并且应该只在需要时使用(当你在同一个文件中有多个模块时)的主要原因。
关于javascript - 为什么 RequireJS 不将 jQuery 传递给函数别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131076/