在 select2 中获取当前输入
Get current input in select2
我正在对多个输入初始化 select2。但是,在调用 AJAX 获取项目时,我需要传递一个附加参数,该参数存储在我应用 select2 的每个输入的 data-id
属性中。所以我需要获得对当前输入的引用。
这是一个例子:
<input class="event-period" data-id="1"/>
<input class="event-period" data-id="2"/>
<script type="text/javascript">
$('.event-period').select2({
ajax: {
url: "/some-url/",
dataType: 'json',
delay: 250,
data: function (params) {
// need to get data-id of current input here
// the "this" keyword is the ajax object, so I can't use that
return {
query: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
}
}
});
</script>
在定义输入时使用 "each()" JQuery 函数
$('.event-period').each(function(){
var id = $(this).attr("data-id");
$(this).select2({
ajax: {
url: "/some-url/",
dataType: 'json',
delay: 250,
data: function (params) {
alert(id); //<- now you can get this
// need to get data-id of current input here
// the "this" keyword is the ajax object, so I can't use that
return {
query: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
}
}
});
});
我正在对多个输入初始化 select2。但是,在调用 AJAX 获取项目时,我需要传递一个附加参数,该参数存储在我应用 select2 的每个输入的 data-id
属性中。所以我需要获得对当前输入的引用。
这是一个例子:
<input class="event-period" data-id="1"/>
<input class="event-period" data-id="2"/>
<script type="text/javascript">
$('.event-period').select2({
ajax: {
url: "/some-url/",
dataType: 'json',
delay: 250,
data: function (params) {
// need to get data-id of current input here
// the "this" keyword is the ajax object, so I can't use that
return {
query: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
}
}
});
</script>
在定义输入时使用 "each()" JQuery 函数
$('.event-period').each(function(){
var id = $(this).attr("data-id");
$(this).select2({
ajax: {
url: "/some-url/",
dataType: 'json',
delay: 250,
data: function (params) {
alert(id); //<- now you can get this
// need to get data-id of current input here
// the "this" keyword is the ajax object, so I can't use that
return {
query: params.term,
page: params.page
};
},
processResults: function (data, page) {
return {
results: data.items
};
}
}
});
});