简体   繁体   English

使用 HTML5 data-* 属性初始化 Javascript Select2 控制器

[英]Initialize Javascript Select2 controller using HTML5 data-* attributes

I'm trying to manage select2 library in order to augment the capabilities of natives select html controls.我正在尝试管理select2 库以增强本地选择 html 控件的功能。

According to the official documentation (very compressed) it says that for using select2 you only need to download they CSS and JavaScript files and that is (and also, implicitly assumed, that you need jQuery).根据官方文档(非常压缩),它说使用 select2 你只需要下载它们的 CSS 和 JavaScript 文件,也就是说(并且隐含地假设你需要 jQuery)。

So, there is a way of initializing select using HTML5 data attributes , but I am not getting it;所以,有一种使用HTML5 数据属性初始化选择的方法,但我没有得到它; I'm trying to follow their example.我正在努力学习他们的榜样。 Perhaps I am missing some important note here.也许我在这里遗漏了一些重要的说明。

Here is the HTML I am trying to do这是我正在尝试做的 HTML

<!DOCTYPE html>
<html>

  <head>
      <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
      <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
      <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
  </head>

  <body>
    <h1>Hello Select2</h1>
  <div>
      <select multiple id="a_select" data-tags="true" data-placeholder="Select an option" data-allow-clear="true" style="width:100%">
        <option value="AL">Alabama</option>
        <option value="WY">Wyoming</option>
      </select>
  </div> 

  </body>

</html>

Also a link to plunker, to have a live example ready to go.还有一个指向 plunker 的链接,以准备好一个现场示例。 https://plnkr.co/edit/Xk101K3sowAYQwbRCFez?p=preview https://plnkr.co/edit/Xk101K3sowAYQwbRCFez?p=preview

PS: I can achieve the desired result thought JavaScript, but is quite annoying to don't know what is not working when i just followed the example on the official site. PS:我可以通过 JavaScript 实现预期的结果,但是当我只是按照官方网站上的示例进行操作时,不知道什么不起作用,这很烦人。

You're not initializing Select2 anywhere... data-* attributes let you override default configuration, but you still need to kick off the plugin:你没有在任何地方初始化 Select2... data-*属性让你覆盖默认配置,但你仍然需要启动插件:

<script>$('select').select2();</script>

https://plnkr.co/edit/RPObSPVl8jlZgtedsK38?p=preview https://plnkr.co/edit/RPObSPVl8jlZgtedsK38?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM