22

我是新手,需要 js,问题是我不太了解如何加载 jQuery 插件。

我想加载多个插件,但我已经遇到了第一个插件的问题,选择的插件

js

//site full url
var siteUrl = window.location.protocol+"//"+window.location.host + "/";

requirejs.config({
    baseUrl: siteUrl + "assets/js",

    paths: {
        "jquery": "libs/jquery",
        "jquery-ui": "libs/jquery-ui",
        "bootstrap": "libs/bootstrap",
        "scripts": "scripts",
        "plugins": "plugins",
    }, 
});

requirejs(['jquery', 'jquery-ui', 'bootstrap', 'plugins/chosen'],
function($, chosen){
    $('.chzn-select').chosen();
});

我的测试html

<select data-placeholder="Choose a country..." style="width:350px;" class="chzn-select">
    <option value="">Test</option>
    <option value="">Test</option>
    <option value="">Test</option>
</select>

当我尝试加载它时,我收到以下错误

TypeError: $ is not a function


...tion(){"in"==self.hoverState&&self.show()},self.options.delay.show),void 0):self...

bootstrap.js (line 6)

TypeError: $(...).chosen is not a function


$('.chzn-select').chosen();

有人可以指出我做错了什么吗?

4

2 回答 2

42

当您加载依赖项时,requirejs 会同时加载它们。当您收到该错误时,这意味着您的插件在加载 jQuery 之前已被加载和执行。您需要设置一个 shim 来告诉 requirejs 该插件依赖于已加载的 jQuery。

此外,大多数 jQuery 插件不支持 AMD,因此您还需要告诉 requirejs 寻找什么来告诉它正确加载的脚本。您可以使用 shim 中的“导出”条目来执行此操作。

我也不相信 jqueryUI 是 AMD 感知的,所以垫片中的一个条目可能也是为了这个。我不使用引导程序,所以我不确定你是否需要任何东西。

这是您的插件和 jQueryUI 的 shim,将其添加到您对 requirejs.config 的调用中:

shim: {
    'plugins\chosen': {
        deps: [ 'jquery' ],
        exports: 'jQuery.fn.chosen'
    },
    'jquery-ui': {
        deps: [ 'jquery' ],
        exports: 'jQuery.ui'
    }
}

你可能还有一些我还没有看到的问题,但这至少应该让你继续前进。此外,这可能值得一读:http ://requirejs.org/docs/api.html#config-shim 。如果您还没有,我肯定会建议您阅读整页。

于 2013-02-07T17:28:36.103 回答
4

嗨,我想在这里告诉你,如果你想包含非 AMD 脚本(不包括 define() 调用),我们使用 shim config 。我想用一个简单的 jquery hightlight 插件示例来解释。

这将是您定义所有路径的配置文件

paths:{
    "jquery":"/path/to/jquery",
    "jgHighlight":"/path/to/jquery.highlight"
},
   shim:{

        deps:["jquery"], // jquery.highlight dependeps on jquery so it will load after jquery has been loaded 
        exports:"jqHighlight"

   }

现在在以 define 开头的模块中,像这样包含 jqHighlight

define(["requireModulesArray","jgHighlight"],function(requiredModulesAliasArray){

   // no need to include any alias for jgHighlight in function(...)
   //use it like this now

     $("#divT").highlight("someText");

});

类似地,将包含和使用其他非 amd 模块。谢谢

于 2015-02-19T10:37:59.410 回答