如何将 select2 与 Meteor 一起使用?

How to use select2 with Meteor?

谁能给我解释一下 select2 如何与 Meteor 一起工作?我正在使用 zimme:select2-boostrap3-css 但我不知道如何使用它。

我检查了两个原来的select2 github page and the one from the package。第一个解释了如何在没有 Meteor 的情况下使用它。

我是否只是将 jQuery 代码添加到我的一个 *.js 文件中才能使其正常工作?

在HTML中:

<select class="input" id="clientName" name="clientName">
    {{#each getClients}}
        <option value="{{clientName}}" data-id={{_id}}>{{clientName}}</option>
    {{/each}}
</select>

在 JS 中:

$("#clientName").select2();

因为这行不通。

加载我的页面时出现此错误 Uncaught TypeError: $(...).select2 is not a function

Uncaught TypeError: $(...).select2 is not a function

上面的错误发生是因为您没有为 Select2 包含 JavaScript,如评论中所指出的那样。气氛 package you linked to 只是为了在 现有的 Select2 包之上提供 Bootstrap 风格

您还应该包括 meteor add natestrauser:select2

您可能 运行 遇到的下一个问题是,当 JavaScript 运行 时,<select class="input" > 可能不会加载到 DOM 中,因此 $("#clientName") 找不到任何东西。要等到页面加载后再初始化 Select2,您应该将代码包装在 jQuery 的 DOM 就绪函数 $(function(){}); 中,并将其包装在 Meteor.Startup() 中以备不时之需像这样:

Meteor.startup(function () {
  $(function(){
    $("#clientName").select2();
  });
});

Working Demo in Meteorpad

进一步阅读: