[英]How to find the id of the active Select2 element
I have a form with multiple select menus generated with Select2 (version 4) where the id value of each select element is set dynamically. 我有一个带有Select2(版本4)生成的多个选择菜单的表单,其中每个select元素的id值是动态设置的。 I'd like to find the id of the select element the user clicks on. 我想找到用户点击的select元素的id。
I can get this to work 我可以让这个工作
$('.js-example-tokenizer-ajax-data').on('select2:open', function (evt) {
myValue = $(this).attr('id');
});
But I need to use myValue
as a parameter for data
inside an ajax call so an option getting the id of the active select2 element is needed. 但我需要使用myValue
作为ajax调用中data
的参数,因此需要获取活动select2元素的id的选项。 I've seen posts that suggest var selectedEle = $(document.activeElement)
but I don't know how to get the id from there. 我看过帖子建议var selectedEle = $(document.activeElement)
但我不知道如何从那里获取id。
UPDATE UPDATE
It seems I can include this as the value for the data parameter 我似乎可以将其作为data参数的值包含在内
data: getSelectedElement(function() {
return JSON.stringify({variable: myValue})
}),
with the function as 功能如
function getSelectedElement(callback) {
$('.js-example-tokenizer-ajax-data').on('select2:opening', function (evt) {
myValue = $(this).attr('id');
callback();
});
}
But there are still some timing issues since the ajax seems to fire before a select element is clicked since when I load the page I get an error 'NoneType' object has no attribute '__getitem__'
I gather since there was no value for myValue when the page loaded. 但是仍有一些时间问题,因为ajax似乎在单击select元素之前触发,因为当我加载页面时我收到错误'NoneType' object has no attribute '__getitem__'
我收集了因为myValue没有值时页面已加载。
Are there other options to get the id of the selected select2 element? 是否有其他选项来获取所选select2元素的id? Alternatively, are there ways to sort out the timing issue? 或者,有没有办法解决时间问题?
If var selectedEle = $(document.activeElement)
does in fact get the element that you want you can simply do document.activeElement.id
. 如果var selectedEle = $(document.activeElement)
确实获得了你想要的元素,你可以简单地做document.activeElement.id
。
In a different stack overflow answer someone said this.context
will give you the correct element, in which case this.context.id
would give you the id. 在一个不同的堆栈溢出回答有人说this.context
会给你正确的元素,在这种情况下this.context.id
会给你id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.