2013-09-29 35 views
1

我在输入字段上使用Select2作为多选。我试图找出正在被点击的选项,但如果我查看点击选项(“选择选择”)时发生的事件,我只能找到event.target.value,它是包含所有选定选项的数据数组(选择)。基本上我想访问点击的值,所以我可以让用户在该特定选项中编辑自定义属性。我怎么能这样做呢?在Select2倍数中获取/设置点击选择的值

的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" 
}); 

回答

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'); 
}); 

我相应地更新your jsfiddle

+0

您的解决方案完美无缺。非常感谢! –

+1

您能否分享一下您使用的Select2版本来实现?在当前文档中,我找不到任何选择选择的事件:http://ivaynberg.github.io/select2/#documentation – Marklar

+0

@Marklar,你找到答案了。我也没有找到选择选择的事件。大卫你使用哪个版本? – Erlan

0

尝试

var selected = {}; 
$(test).change(function() { 
    var selections = $(this).select2('data'); 
    $.each(selections, function (idx, obj) { 
     if (!selected[obj.id]) { 
      selected[obj.id] = obj; 
      $('#selectedText').text(JSON.stringify(obj)); 
      return false; 
     } 
    }) 
}); 

演示:Fiddle

注:有没有看到是否有内置支持要做到这一点,但定制实施