如何使用 jquery 每次循环命名 select id 元素?

How to name select id element using jquery each looping?

我想在表单中实现 jquery select2 插件。我在命名文本框以便触发 select2 时遇到问题。这是 html:

<select id="select1"></select>
<select id="select2"></select>
<select id="select3"></select>

下面是从数据库中检索数据的代码:

$('#select').select2({
        ajax: {
                url: "get_member.php",
                dataType: 'json',
                delay: 200,
                data: function (params) {
                    return {
                        q: params.term
                    };
                },
                processResults: function (data) {

                    return {
                        results: data
                    };
                },
                cache: true
            }
        });

如何将 id 元素从 select 更改为 select1、select2 等?我读到可以在每个循环中使用 jquery,但我不知道如何使用。

使用每个循环

$('select[id^="select"]').each(function () {
    $(this).select2();
});

方法很少

1. Wrap your selects or using form with id, so it became like this:

html

<form id="niceform">
<select id="select1"></select>
<select id="select2"></select>
<select id="select3"></select>
</form>

js

$('#niceform select').select2({ ... });

2. Use jQuery special selector:

$('select[id^=select]').select2({ ... });

that will select all select element which have id attribute start with word "select"

3. Give them classes:

html

<select class="select" id="select1"></select>
<select class="select" id="select2"></select>
<select class="select" id="select3"></select>

js

$('.select').select2({ ... });

实际上您不需要循环。

将它们分组 class:

<div class="select">
    <select id="select1"></select>
    <select id="select2"></select>
    <select id="select3"></select>
</div>

然后 jQuery:

$.map($('.select').children(), function (ele, i) {
    doYourThing($(ele));
  });