简体   繁体   English

带有多个选择标记的jQuery select2

[英]jQuery select2 with multiple select tags

I'm using jQuery Select2 2.1 and trying to apply it to multiple select tags with same id class. 我正在使用jQuery Select2 2.1并尝试将其应用于具有相同id类的多个select标签。 My code looks like this: 我的代码看起来像这样:

<select id="e1" style="width: 300px">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
    <option value="NY">New York</option>
</select>
...
<select id="e1" style="width: 300px">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
    <option value="NY">New York</option>
</select>

The javascript code is use is: javascript代码使用的是:

<script>
    $(document).ready(function() { $('#e1').select2(); });
</script>

The problem is that only the first select tag gets the proper select2 class. 问题是只有第一个select标签才能获得正确的select2类。 I don't know if the select2 allows this type of usage (i could not identify this information in documentation), but another options would be the increment the javascript function { $('#e1').select2(); } 我不知道select2是否允许这种类型的使用(我无法在文档中识别此信息),但另一个选项是增加javascript函数{ $('#e1').select2(); } { $('#e1').select2(); } to permit { $('#e(1..999)').select2(); } { $('#e1').select2(); } ,以允许{ $('#e(1..999)').select2(); } { $('#e(1..999)').select2(); } , after i will adjust php code <select id="e<?php echo $i ?>" style="width: 300px"> , where $i is incremented. { $('#e(1..999)').select2(); } ,i之后将调整PHP代码<select id="e<?php echo $i ?>" style="width: 300px"> ,其中$ i递增。

How can i achieve this? 我怎样才能实现这一目标? Thanks. 谢谢。

Firstly, do you really need to have 2 selects with the same id? 首先,你真的需要有两个具有相同ID的选择吗?

Secondly, to match both, you can do $('[id="e1"]').select2(); 其次,为了匹配两者,你可以做$('[id="e1"]').select2(); - But you shouldn't imo. - 但你不应该imo。

Using multiple elements with the same ID is VERY bad practice. 使用具有相同ID的多个元素是非常糟糕的做法。 Use a class instead...that's what they're for. 改为使用一个类......这就是他们的目的。

HTML: HTML:

<select class="select2" style="width: 300px">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
    <option value="NY">New York</option>
</select>
...
<select class="select2" style="width: 300px">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
    <option value="NY">New York</option>
</select>

JavaScript: JavaScript的:

$(document).ready(function() { $('.select2').select2(); });

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

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