在Select2 multiple中获取/设置单击选项的值

Mat*_*son 1 javascript jquery jquery-select2

我在输入字段上使用Select2作为多选.我试图找出被点击的选项,但如果我查看单击选项("choice-selected")时抛出的事件,我可以找到的是event.target.value,它是包含所有选定选项的数据数组(选择).基本上我想访问点击的值,这样我就可以让用户在该特定选项中编辑自定义属性.我怎么能这样做呢?

JSFiddle问题:http://jsfiddle.net/JtTTF/

$(test).bind("choice-selected", function(e) {
 alert(e.target.value);
    // this is where i would like to access the clicked choice id so i can edit the custom data attribute "reason"
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*lsh 6

我也碰到了这个.在检查了select2.js源代码之后,我发现选择选择的事件传递了第二个参数:你点击的dom元素.

此dom元素包含一个带有键"select2-data"的数据对象.

您的代码可能如下所示:

$(test).on("choice-selected", function(e, choice) {
    var data = $(choice).data('select2-data');
    alert(data.reason ? 'Reason: ' + data.reason : 'No Reason');
});
Run Code Online (Sandbox Code Playgroud)

我相应地更新了你的jsfiddle.